﻿// user access global
var accessList = null;

// editor page globals
var editorIndex = 0;  // index to tag editors
var editors = [];  // array of all open editors
var activeEditor = null;  // currently active/open editor
var activeEditorPageId = null;
var activeReturnHref = "";
var activeDrillLevel = -1;
var sessionId = -1;
var userId = -1;

// schedule editor globals
var scheduleEditorHeaders = [];
var scheduleEditorListLookupIds = [];
var scheduleEditorHeader = null;
var scheduleEditorReturnButton = null;
var scheduleEditorCancelButton = null;
var scheduleEditorDrillHeader = "";
var scheduleEditorIsModified = 0;
var scheduleEditorEditChoice = "";
var scheduleEditorNextWeek = false;
var scheduleEditorPrevWeek = false;
var scheduleEditorTimer = null;
var openSchedule = false;

// package editor globals
var packageEditorPackageId = "";
var packageEditorPackageName = "";
var packageEditorPackageDate = "";
var packageEditorPackageTime = "";
var packageEditorHeader = null;
var packageEditorReturnButton = null;
var packageEditorCancelButton = null;
var packageEditorPeca = null;
var packageEditorPecaEl = null;
var packageEditorDrillHeader = "";
var packageEditorIsModified = 0;
var packageEditorEditChoice = "";
var packageEditorTimer = null;

// event editor globals
var eventEditorEventId = "";
var eventEditorEventName = "";
var eventEditorHeader = null;
var eventEditorReturnButton = null;
var eventEditorCancelButton = null;
var eventEditorPeca = null;
var eventEditorDrillHeader = "";
var eventEditorIsModified = 0;
var eventEditorEditChoice = "";
var eventEditorDurationUpdated = false;
var eventEditorTimer = null;

// combo editor globals
var comboEditorComboId = "";
var comboEditorComboName = "";
var comboEditorHeader = null;
var comboEditorReturnButton = null;
var comboEditorCancelButton = null;
var comboEditorPeca = null;
var comboEditorDrillHeader = "";
var comboEditorIsModified = 0;
var comboEditorEditChoice = "";
var comboEditorSFLoaded = false;
var comboEditorLoaded = false;
var comboEditorTimer = null;

// asset editor globals
var assetEditorAssetId = "";
var assetEditorAssetName = "";
var assetEditorHeader = null;
var assetEditorReturnButton = null;
var assetEditorReturnChoice = "";
var assetEditorCancelButton = null;
var assetEditorPeca = null;
var assetEditorDrillHeader = "";
var assetEditorIsModified = 0;
var assetEditorEditChoice = "";
var assetEditorTimer = null;
var assetThumbnailVidPathCfg = "";
var assetThumbnailVidSizeCfg = "";
var assetThumbnailJPEGPathCfg = "";
var assetThumbnailJPEGSizeCfg = "";

// live control global
var searchChoice = "";
var liveControlPackageId = "";
var liveControlEditorTimer = null;
var liveControlTickerEditorTextArea = null;

// multi package global
var multiPackageListLookupIds = [];
var multiPackageHeader = null;
var multiPackageReturnButton = null;
var multiPackageCancelButton = null;
var multiPackageCount = 0;
var multiPackageIsModified = 0;
var multiPackageTimer0 = null;
var multiPackageTimer1 = null;
var multiPackageTimer2 = null;

// ticker eidtor globals
var activeTickerEditor = null;

// string tags
var stringTagDefaultTickerEditorTextArea = null;

// function to create and call generic post xml for stored procedure
function callAjaxPost(request, sProc, readyFx) {
    // create xml
    var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
    xmlStr += "<ROOT>";
    xmlStr += sProc;
    xmlStr += "</ROOT>";
    url = "AjaxPost.aspx";
    request.open('POST', url, true);
    request.setRequestHeader("Content-Type", "text/xml");
    request.send(xmlStr);
    request.onreadystatechange = readyFx;
}

// functions to load package editor
var liveControlRequest = new XMLHttpRequest();	
function loadLiveControlEditor () {
    // make request to db to get live control info
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetPackageLiveControl\" />";
    callAjaxPost(liveControlRequest, sProc, processLiveControlLoadStateChange);
	$('pageContainer').addClassName('fadedBG');
	$('loadingMsg').style.display = "block";
}

// functions to load package editor
var packageRequest = new XMLHttpRequest();	
function loadPackageEditor () {
    // make request to db to get package info
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetPackage\" ID=\"" + packageEditorPackageId + "\" />";
    callAjaxPost(packageRequest, sProc, processPackageLoadStateChange);
	$('pageContainer').addClassName('fadedBG');
	$('loadingMsg').style.display = "block";
}

// functions to load package editor
var multiPackageRequest = [];
function loadMultiPackageEditor () {
    $('pageContainer').addClassName('fadedBG');
	$('loadingMsg').style.display = "block";
    
    // make request to db to get info for packages
    for (var i=0; i<multiPackageCount; i++) {
        var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetPackage\" ID=\"" + multiPackageListLookupIds[i] + "\" />";
        multiPackageRequest[i] = new XMLHttpRequest();
        var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
        xmlStr += "<ROOT>";
        xmlStr += sProc;
        xmlStr += "</ROOT>";
        var url = "AjaxPost.aspx";
        multiPackageRequest[i].open('POST', url, false);
        multiPackageRequest[i].setRequestHeader("Content-Type", "text/xml");
        multiPackageRequest[i].send(xmlStr);
        
        if (multiPackageRequest[i].readyState == 4) {
	        if (multiPackageRequest[i].status == 200) {
	            if (multiPackageRequest[i].responseXML != null) {
                    continue;
                }
            }
        }     
        //callAjaxPost(multiPackageRequest[i], sProc, processMultiPackageLoadStateChange);
    }
    loadMultiPackagePage();
}

// functions to load event editor
var eventRequest = new XMLHttpRequest();	
function loadEventEditor () {
    // make request to db to get package info
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetEvent\" ID=\"" + eventEditorEventId + "\" />";
    callAjaxPost(eventRequest, sProc, processEventLoadStateChange);
	$('pageContainer').addClassName('fadedBG');
	$('loadingMsg').style.display = "block";
}

// functions to load combo editor
var comboRequest = new XMLHttpRequest();	
function loadComboEditor () {
        // make request to db to get combo info 
        var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetCombo\" ID=\"" + comboEditorComboId + "\" />";
        callAjaxPost(comboRequest, sProc, processComboLoadStateChange);
	    $('pageContainer').addClassName('fadedBG');
	    $('loadingMsg').style.display = "block";
}

// functions to load asset editor
var assetRequest = new XMLHttpRequest();	
function loadAssetEditor () {
    // make request to db to get asset info
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetAsset\" ID=\"" + assetEditorAssetId + "\" />";
    callAjaxPost(assetRequest, sProc, processAssetLoadStateChange);
    $('pageContainer').addClassName('fadedBG');
    $('loadingMsg').style.display = "block";
}

// ajax state change handler
function processLiveControlLoadStateChange () {
	if (liveControlRequest.readyState == 4) {
		if (liveControlRequest.status == 200) {
		    if (liveControlRequest.responseXML != null) {
		        loadLiveControlPage();
		        var packageObj = liveControlRequest.responseXML.getElementsByTagName('PACKAGE')[0];
		        if (packageObj.getAttribute('ID') > 0) {
		            // call sproc to show object open
	                objForEditOpen(packageObj.getAttribute('ID'),1); 
		        }
		    }
		}
	} 
}

var loadedSearchFields = [1,0,0,0,0];
// ajax state change handler
var scheduleSFRequest = new XMLHttpRequest();
function processScheduleSFRequestChange () {
	if (scheduleSFRequest.readyState == 4) {
		if (scheduleSFRequest.status == 200) {
		    if (scheduleSFRequest.responseXML != null) {
		        loadedSearchFields[1] = 1;
		        loadSearchFields();
		    }
		}
	} 
}

// ajax state change handler
//var multiPackageLoadedCount = 0;
//var multiPackageLoadedArr = [0,0,0]
//function processMultiPackageLoadStateChange () {
//    if ( (multiPackageRequest[0] != null) && (multiPackageLoadedArr[0] != 1) ) {
//        if (multiPackageRequest[0].readyState == 4) {
//	        if (multiPackageRequest[0].status == 200) {
//	            if (multiPackageRequest[0].responseXML != null) {
//	                multiPackageLoadedArr[0] = 1;
//	                multiPackageLoadedCount++;
//	                loadMultiPackagePage();
//	            }
//	        }
//        } 
//    } else if ( (multiPackageRequest[1] != null) && (multiPackageLoadedArr[1] != 1) ) {
//        if (multiPackageRequest[1].readyState == 4) {
//	        if (multiPackageRequest[1].status == 200) {
//	            if (multiPackageRequest[1].responseXML != null) {
//	                multiPackageLoadedArr[1] = 1;
//	                multiPackageLoadedCount++;
//	                loadMultiPackagePage();
//	            }
//	        }
//        } 
//    } else if ( (multiPackageRequest[2] != null) && (multiPackageLoadedArr[2] != 1) ) {
//        if (multiPackageRequest[2].readyState == 4) {
//	        if (multiPackageRequest[2].status == 200) {
//	            if (multiPackageRequest[2].responseXML != null) {
//	                multiPackageLoadedArr[2] = 1;
//	                multiPackageLoadedCount++;
//	                loadMultiPackagePage();
//	            }
//	        }
//        } 
//    }
//}

// ajax state change handler
function processPackageLoadStateChange () {
	if (packageRequest.readyState == 4) {
		if (packageRequest.status == 200) {
		    if (packageRequest.responseXML != null) {
		        loadPackagePage();
		        var packageObj = packageRequest.responseXML.getElementsByTagName('PACKAGE')[0];
		        if (packageObj.getAttribute('ID') > 0) {
		            // call sproc to show object open
	                objForEditOpen(packageObj.getAttribute('ID'),1); 
		        }
		    }
		}
	} 
}

// ajax state change handler
var packageSFRequest = new XMLHttpRequest();	
function processPackageSFRequestChange () {
	if (packageSFRequest.readyState == 4) {
		if (packageSFRequest.status == 200) {
		    if (packageSFRequest.responseXML != null) {
		        loadedSearchFields[2] = 1;
		        loadSearchFields();
		    }
		}
	} 
}

// ajax state change handler
function processEventLoadStateChange () {
	if (eventRequest.readyState == 4) {
		if (eventRequest.status == 200) {
		    if (eventRequest.responseXML != null) {
		        loadEventPage();
		        var eventObj = eventRequest.responseXML.getElementsByTagName('EVENT')[0];
	            if (eventObj.getAttribute('ID') > 0) {
	                // call sproc to show object open
                    objForEditOpen(eventObj.getAttribute('ID'),2); 
                }
            }
		}
	} 
}

// ajax state change handler
var eventSFRequest = new XMLHttpRequest();	
function processEventSFRequestChange () {
	if (eventSFRequest.readyState == 4) {
		if (eventSFRequest.status == 200) {
		    if (eventSFRequest.responseXML != null) {
		        loadedSearchFields[3] = 1;
		        loadSearchFields();
		    }
		}
	} 
}

// ajax state change handler
function processComboLoadStateChange () {
	if (comboRequest.readyState == 4) {
		if (comboRequest.status == 200) {
			if (comboRequest.responseXML != null) {
			    loadComboPage();
			    //updateComboSFOptions(); calling in previous function
			    var combo = comboRequest.responseXML.getElementsByTagName('ASSET')[0];
	            if (combo.getAttribute('ID') > 0) {
	                // call sproc to show object open
                    objForEditOpen(combo.getAttribute('ID'),3); 
                }
			}
		}
	} 
}

// ajax state change handler
var comboSFRequest = new XMLHttpRequest();	
function processComboSFRequestChange () {
	if (comboSFRequest.readyState == 4) {
		if (comboSFRequest.status == 200) {
		    if (comboSFRequest.responseXML != null) {
		        loadedSearchFields[4] = 1;
		        loadSearchFields();
		        //updateComboSFOptions();
		    }
		}
	} 
}

// ajax state change handler
function processAssetLoadStateChange () {
	if (assetRequest.readyState == 4) {
		if (assetRequest.status == 200) {
			if (assetRequest.responseXML != null) {
			    loadAssetPage();
			    var asset = assetRequest.responseXML.getElementsByTagName('ASSET')[0];
	            if (asset.getAttribute('ID') > 0) {
	                // call sproc to show object open
                    objForEditOpen(asset.getAttribute('ID'),4); 
                }
			}
		}
	} 
}

// function to call sproc to open an object for edit
var openRequest = null;
function objForEditOpen(id, level) {
    // make request to db set object as open
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_ObjForEditOpen\" ID=\"" + id + "\" Level=\"" + level + "\" />";
    openRequest = new XMLHttpRequest();
    callAjaxPost(openRequest, sProc, processOpenRequestStateChange);
    
    objForEditKeepOpen(id, level);
}	    

// function to call sproc to open a schedule for edit
var openScheduleRequest = null;
function scheduleForEditOpen(index, date) {   
    // make request to db set object as open
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_ScheduleForEditOpen\" Date=\"" + date + "\" />";
    openScheduleRequest = new XMLHttpRequest();
    callAjaxPost(openScheduleRequest, sProc, processOpenScheduleRequestStateChange);
    
    scheduleForEditKeepOpen(index);
}	

// function to call sproc to close an object for edit
var closeRequest = null;
function objForEditClose() {
    if (activeEditorPageId != 'multiPackage') {
        // get id
        var level = -1;
        var objXML = null;
        if (activeEditorPageId == 'packageEditor') objXML = packageRequest.responseXML.getElementsByTagName('PACKAGE')[0];
        else if (activeEditorPageId == 'eventEditor') objXML = eventRequest.responseXML.getElementsByTagName('EVENT')[0];
        else if (activeEditorPageId == 'comboEditor') objXML = comboRequest.responseXML.getElementsByTagName('ASSET')[0];
        else if (activeEditorPageId == 'assetEditor') objXML = assetRequest.responseXML.getElementsByTagName('ASSET')[0];
        else if (activeEditorPageId == 'liveControl') objXML = liveControlRequest.responseXML.getElementsByTagName('PACKAGE')[0];

        var id = objXML.getAttribute('ID');
        
        if (id > 0) {
            if (activeEditorPageId == 'packageEditor') {
                clearTimeout(packageEditorTimer);
            } else if (activeEditorPageId == 'eventEditor') {
                clearTimeout(eventEditorTimer);
            } else if (activeEditorPageId == 'comboEditor') {
                clearTimeout(comboEditorTimer);
            } else if (activeEditorPageId == 'assetEditor') {
                clearTimeout(assetEditorTimer);
            } else if (activeEditorPageId == 'liveControl') {
                clearTimeout(liveControlEditorTimer);
            }
        
            // make request to db to close object
            var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_ObjForEditClose\" ID=\"" + id + "\" Level=\"" + activeEditor.systemLevel + "\" />";
            closeRequest = new XMLHttpRequest();
            var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
            xmlStr += "<ROOT>";
            xmlStr += sProc;
            xmlStr += "</ROOT>";
            var url = "AjaxPost.aspx";
            closeRequest = new XMLHttpRequest();
            closeRequest.open('POST', url, false);
            closeRequest.setRequestHeader("Content-Type", "text/xml");
            closeRequest.send(xmlStr);
            //callAjaxPost(closeRequest, sProc, null);   
        }
    } else if (activeEditorPageId == 'multiPackage') {
        for (var i=0; i<multiPackageCount; i++) {
//            var objXML = multiPackageRequest[i].responseXML.getElementsByTagName('PACKAGE')[0];
//            var id = objXML.getAttribute('ID');
            var id = activeEditor.listLookupIds[i];
            if (id > 0) {
                if (i == 0) clearTimeout(multiPackageTimer0);
                if (i == 1) clearTimeout(multiPackageTimer1);
                if (i == 2) clearTimeout(multiPackageTimer2);
                
                // make request to db to close object
                var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_ObjForEditClose\" ID=\"" + id + "\" Level=\"1\" />";
                closeRequest = new XMLHttpRequest();
                var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
                xmlStr += "<ROOT>";
                xmlStr += sProc;
                xmlStr += "</ROOT>";
                var url = "AjaxPost.aspx";
                closeRequest = new XMLHttpRequest();
                closeRequest.open('POST', url, false);
                closeRequest.setRequestHeader("Content-Type", "text/xml");
                closeRequest.send(xmlStr);
                //callAjaxPost(closeRequest, sProc, null);   
            }
        }
    }
}	

// function to call sproc to close an object for edit
//var closeScheduleRequest = null;
//function scheduleForEditClose(index, date) {    
//    clearTimeout(scheduleEditorTimer);
//        
//    // make request to db to close object
//    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_ScheduleForEditClose\" Date=\"" + date + "\" />";
//    closeScheduleRequest = new XMLHttpRequest();
//    callAjaxPost(closeScheduleRequest, sProc, null);   
//}	

// function to call stored procedure to keep an object open for edit
var keepOpenRequest = null;
function objForEditKeepOpen(id, level) {   
    if (activeEditorPageId != 'multiPackage') {
        if (activeEditorPageId == 'packageEditor') {
            packageEditorTimer = setTimeout('objForEditKeepOpen(' + id + ', ' + level + ')', 60000);
        } else if (activeEditorPageId == 'eventEditor') {
            eventEditorTimer = setTimeout('objForEditKeepOpen(' + id + ', ' + level + ')', 60000);
        } else if (activeEditorPageId == 'comboEditor') {
            comboEditorTimer = setTimeout('objForEditKeepOpen(' + id + ', ' + level + ')', 60000);
        } else if (activeEditorPageId == 'assetEditor') {
            assetEditorTimer = setTimeout('objForEditKeepOpen(' + id + ', ' + level + ')', 60000);
        } else if (activeEditorPageId == 'liveControl') {
            liveControlEditorTimer = setTimeout('objForEditKeepOpen(' + id + ', ' + level + ')', 60000);
        }
        
        // make request to db to keep object open
        var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_ObjForEditOpen\" ID=\"" + id + "\" Level=\"" + level + "\" />";
        keepOpenRequest = new XMLHttpRequest();
        callAjaxPost(keepOpenRequest, sProc, null);  
    } else if (activeEditorPageId == 'multiPackage') {
        for (var i=0; i<multiPackageCount; i++) {
            if (i == 0) multiPackageTimer0 = setTimeout('objForEditKeepOpen(' + id + ', ' + level + ')', 60000);
            if (i == 1) multiPackageTimer1 = setTimeout('objForEditKeepOpen(' + id + ', ' + level + ')', 60000);
            if (i == 2) multiPackageTimer2 = setTimeout('objForEditKeepOpen(' + id + ', ' + level + ')', 60000);
            
            // make request to db to keep object open
            var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_ObjForEditOpen\" ID=\"" + id + "\" Level=\"" + level + "\" />";
            keepOpenRequest = new XMLHttpRequest();
            callAjaxPost(keepOpenRequest, sProc, null);  
        }
    }

}

// function to call stored procedure to keep an object open for edit
var keepOpenScheduleRequest = null;
function scheduleForEditKeepOpen(index) {   
    editors.first().ddLists[index].scheduleForEditKeepOpen();
}

// ajax state change handler
function processOpenRequestStateChange () {
	if (openRequest.readyState == 4) {
		if (openRequest.status == 200) {
			if (openRequest.responseXML != null) {
			    if (openRequest.responseXML.getElementsByTagName('USER').length > 0) {
			        // alert user that the object is already open
			        showOpenForEdit();
			        // disable save, savecopy, cancel
			        var saveStr = activeEditorPageId + "_Save";
			        var saveCopyStr = activeEditorPageId + "_SaveCopy";
			        var cancelStr = activeEditorPageId + "_Cancel";
			        $(saveStr).setAttribute('disabled', 'disabled');
			        if ( (activeEditorPageId != 'multiPackage') && (activeEditorPageId != 'liveControl') ) $(saveCopyStr).setAttribute('disabled', 'disabled');
			        if (activeEditorPageId != 'liveControl') $(cancelStr).setAttribute('disabled', 'disabled');
			    }
			}
		}
	} 
}

// ajax state change handler
function processOpenScheduleRequestStateChange () {
	if (openScheduleRequest.readyState == 4) {
		if (openScheduleRequest.status == 200) {
			if (openScheduleRequest.responseXML != null) {
			    if (openScheduleRequest.responseXML.getElementsByTagName('USER').length > 0) {
			        // alert user that the schedule is already open
			        showOpenScheduleForEdit(openScheduleRequest.responseXML);
			        // disable save, savecopy, cancel
			        var saveStr = activeEditorPageId + "_Save";
			        var cancelStr = activeEditorPageId + "_Cancel";
			        $(saveStr).setAttribute('disabled', 'disabled');
			        $(cancelStr).setAttribute('disabled', 'disabled');
			    }
			}
		}
	} 
}

// function to show popup of open for user edit
function showOpenForEdit() {
    var objStr = "";
    if (activeEditor.systemLevel == 1) objStr = "package";
    else if (activeEditor.systemLevel == 2) objStr = "event";
    else if (activeEditor.systemLevel == 3) objStr = "combo";
    else if (activeEditor.systemLevel == 4) objStr = "asset";
    
    var user = openRequest.responseXML.getElementsByTagName('USER')[0];
    var fName = user.getAttribute('FirstName');
    var lName = user.getAttribute('LastName');
    var email = user.getAttribute('Email');
    var phone = user.getAttribute('Phone');
    
    $('openForEdit_Span').innerHTML = "Unable to Edit";
    var label = $('openForEdit_Label');
    label.innerHTML = "This " + objStr + " is currently being edited by " + fName + " " + lName;
    label.innerHTML += " (email: " + email + ", phone: " + phone + ").  You can view the " + objStr;
    label.innerHTML += " but will not be able to save any changes."
    $('openForEditAlert').style.display = "block";
}

// function to show popup of open for user edit
function showOpenScheduleForEdit(responseXML) { 
    if (openSchedule) return;  // return if this is already open
    openSchedule = true;
    var user = responseXML.getElementsByTagName('USER')[0];
    var openScheduleDate = responseXML.getElementsByTagName('OPENSCHEDULETRACKER')[0].getAttribute('OpenForEditDateTime');
    
    var fName = user.getAttribute('FirstName');
    var lName = user.getAttribute('LastName');
    var email = user.getAttribute('Email');
    var phone = user.getAttribute('Phone');
    
    $('openForEdit_Span').innerHTML = "Unable to Edit";
    var label = $('openForEdit_Label');
    label.innerHTML = "The schedule on " + openScheduleDate + " is currently being edited by " + fName + " " + lName;
    label.innerHTML += " (email: " + email + ", phone: " + phone + ").  You can view "
    label.innerHTML += (activeEditor.ddLists.length > 0) ? "these schedules" : "the schedule";
    label.innerHTML += " but will not be able to save any changes."
    $('openForEditAlert').style.display = "block";
}

// loads properties and log info
function loadLiveControlPage () {
	
	searchChoice = "Package";
	
	// make calls to load search params
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"1\" />";
    callAjaxPost(scheduleSFRequest, sProc, processScheduleSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"2\" />";
    callAjaxPost(packageSFRequest, sProc, processPackageSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"3\" />";
    callAjaxPost(eventSFRequest, sProc, processEventSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"4\" />";
    callAjaxPost(comboSFRequest, sProc, processComboSFRequestChange);
		
    // load data
    var packages = liveControlRequest.responseXML.getElementsByTagName('PACKAGE');

    // set up params for drag drop editor
    var headerText = ['LIVE CONTROL'];
    var startTime = new Date(0);
    startTime.setHours(0);
    startTime.setMinutes(0);
    startTime.setSeconds(0);
    var endTime = new Date(0);
    endTime.setHours(0);
    endTime.setMinutes(30);
    endTime.setSeconds(0);
    var listLookupIds = [1];  // this should correlate to zoneid (currently not used)
    
    // load and render drag drop editor
    var ddEditor_Package_0 = new DragDropEditor();
    ddEditor_Package_0.load(1, 'liveControlDDEditorContainer', 1, [1], headerText, packages[0].getAttribute('ID'), listLookupIds, 
                                startTime, endTime, 15, 1, 880, 18, 55, 15, 5, liveControlRequest.responseXML);
    ddEditor_Package_0.render();
    ddEditor_Package_0.activateDD();
    
    // create ticker editor
    populateTickerEditorXML();
    var tickerEditor = new  TickerEditor()
    tickerEditor.load(1, '', '', $('tickerEditorContainer'), tickerEditorResponseXML, liveControlTickerEditorTextArea);
    tickerEditor.render();
    
    
    // load activity log                                 
    var activityLogNodes = liveControlRequest.responseXML.getElementsByTagName('ACTIVITYLOG');
    loadActivityLog(activityLogNodes, $('liveControl_Log'), 'Live Control Package');
        
}

// function to load schedule editor (only called by Editor.aspx)
function loadScheduleEditor () {
  
    // make calls to load search params
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"1\" />";
    callAjaxPost(scheduleSFRequest, sProc, processScheduleSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"2\" />";
    callAjaxPost(packageSFRequest, sProc, processPackageSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"3\" />";
    callAjaxPost(eventSFRequest, sProc, processEventSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"4\" />";
    callAjaxPost(comboSFRequest, sProc, processComboSFRequestChange);
    
    // show week buttons if necessary
    if (scheduleEditorEditChoice == 'EditWeek') {
        $('scheduleEditorNextWeek').style.display = "block";
        $('scheduleEditorNextWeek').setAttribute('onclick', 'loadNextWeek()');
        $('scheduleEditorPrevWeek').style.display = "block";
        $('scheduleEditorPrevWeek').setAttribute('onclick', 'loadPrevWeek()');
        $('scheduleEditorCopyWeek').style.display = "block";
        $('scheduleEditorCopyWeek').setAttribute('onclick', 'showCopyWeekFrom()');
        
    }
    
    // get params for drag drop editor
    var numCols = scheduleEditorHeaders.length;
    
    // get types of lists (in this case all slotted)
    var listTypes = [];
    for (var i=0; i<numCols; i++) {
        listTypes[i] = 0;
    }
        
    // get start and end times (in this case 24 hour day with 30 min increments)
    var startTime = new Date(0);
    startTime.setHours(0);
    startTime.setMinutes(0);
    startTime.setSeconds(0);
    var endTime = new Date(0);
    endTime.setHours(24);
    endTime.setMinutes(0);
    endTime.setSeconds(0);

    // load and render editor into editor container
    var ddEditor_Schedule = new DragDropEditor();
    ddEditor_Schedule.load(0, 'scheduleDDEditorContainer', numCols, listTypes, scheduleEditorHeaders, 
                                '', scheduleEditorListLookupIds, startTime, endTime, 1800, 0, 880, 18, 55, 15, 5, null);
    ddEditor_Schedule.render();
    
    //$('pageContainer').removeClassName('fadedBG');
	//$('loadingMsg').style.display = "none";
}

// loads properties and log info
function loadPackagePage () {
	
    // make calls to load search params   
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"2\" />";
    callAjaxPost(packageSFRequest, sProc, processPackageSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"3\" />";
    callAjaxPost(eventSFRequest, sProc, processEventSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"4\" />";
    callAjaxPost(comboSFRequest, sProc, processComboSFRequestChange);
	
	if (packageEditorEditChoice == "Edit") {
	    // load data into a peca object
	    var packages = packageRequest.responseXML.getElementsByTagName('PACKAGE');
	    //packageEditorPeca = loadPackageFromXML(packages[0]);

	    // set header
	    packageEditorHeader.innerHTML = scheduleEditorDrillHeader + "Package: " + packages[0].getAttribute('Name');

       // fill out form        
       $('packageEditor_Name').value = packages[0].getAttribute('Name');
       $('packageEditor_Id').value = packages[0].getAttribute('ID');
       var duration = parseXMLDate(packages[0].getAttribute('Duration'));
       //$('packageEditor_Duration').value = duration[3] + ":" + duration[4] + ":" + duration[5];
       $('packageEditor_Duration').value = duration[4] + ":" + duration[5];
       $('packageEditor_Duration').setAttribute('disabled', 'disabled');
       var startDate = parseXMLDate(packages[0].getAttribute('ThisStartDate'));
       if (startDate) $('packageEditor_AirDateFrom').value = startDate[1] + "/" + startDate[2] + "/" + startDate[0].substr(2);
       var endDate = parseXMLDate(packages[0].getAttribute('ThisEndDate'));
       if (endDate) $('packageEditor_AirDateTo').value = endDate[1] + "/" + endDate[2] + "/" + endDate[0].substr(2);
       $('packageEditor_Color').style.backgroundColor = "#" + packages[0].getAttribute('ThisColor');
       $('packageEditor_CueStringStart').value = packages[0].getAttribute('CueStringStart');
       $('packageEditor_CueStringEnd').value = packages[0].getAttribute('CueStringEnd');       


        // set up params for drag drop editor
        var headerText = ['EVENT'];
        var startTime = new Date(0);
        startTime.setHours(0);
        startTime.setMinutes(0);
        startTime.setSeconds(0);
        var endTime = new Date(0);
        endTime.setHours(0);
        endTime.setMinutes(duration[4]);
        endTime.setSeconds(duration[5]);
        var listLookupIds = [1];  // this should correlate to zoneid (currently not used)
        
        // load and render drag drop editor
        var ddEditor_Package_0 = new DragDropEditor();
        ddEditor_Package_0.load(1, 'packageDDEditorContainer_0', 1, [1], headerText, packages[0].getAttribute('ID'), listLookupIds, 
                                    startTime, endTime, 15, 1, 880, 18, 55, 15, 5, packageRequest.responseXML);
        ddEditor_Package_0.render();
        ddEditor_Package_0.activateDD();
        
        // update day part restrictions
        if (packages[0].getAttribute('ThisDayPart')) loadDPR(parseInt(packages[0].getAttribute('ThisDayPart'),10));
        
        // load activity log                                 
        var activityLogNodes = packageRequest.responseXML.getElementsByTagName('ACTIVITYLOG');
        loadActivityLog(activityLogNodes, $('packageEditor_Log'), 'Package');
        
    } else if (packageEditorEditChoice == "New") {  	 
	    // set header
	    packageEditorHeader.innerHTML = scheduleEditorDrillHeader + "Package: (new package)";
	    $('packageEditor_SaveCopy').setAttribute('disabled', 'disabled');
	    $('packageEditor_Log').style.display = "none";
	    $('packageEditor_Duration').value = "00:30:00";
           
        // set up params for drag drop editor
        var headerText = ['EVENT'];
        var startTime = new Date(0);
        startTime.setHours(0);
        startTime.setMinutes(0);
        startTime.setSeconds(0);
        var endTime = new Date(0);
        endTime.setHours(0);
        endTime.setMinutes(30);
        endTime.setSeconds(0);
        var listLookupIds = [1];  // this should correlate to zoneid (currently not used)
        
        // load and render drag drop editor
        var ddEditor_Package_0 = new DragDropEditor();
        ddEditor_Package_0.load(1, 'packageDDEditorContainer_0', 1, [1], headerText, -1, listLookupIds, 
                                    startTime, endTime, 15, 1, 880, 18, 55, 15, 5, packageRequest.responseXML);
        ddEditor_Package_0.render();
        ddEditor_Package_0.activateDD();
                
        $('pageContainer').removeClassName('fadedBG');
	    $('loadingMsg').style.display = "none";
	}
	
	// render meta-data fields
    renderMetaData(packageRequest.responseXML);
    // load meta-data fields
    loadMDValues(packageRequest.responseXML, 'packageEditorMetaData');
}

// loads properties and log info  
function loadMultiPackagePage () {

    // check for all packages loaded from db and then reset load count
//    if (multiPackageLoadedCount < multiPackageCount) return;
//    multiPackageLoadedCount = 0;
//    multiPackageLoadedArr = [0,0,0];
    
    for (var i=0; i<multiPackageCount; i++) {
        var packageObj = multiPackageRequest[i].responseXML.getElementsByTagName('PACKAGE')[0];
        if (packageObj.getAttribute('ID') > 0) {
            // call sproc to show object open
            objForEditOpen(packageObj.getAttribute('ID'),1); 
        }
    }
	
    // make calls to load search params   
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"2\" />";
    callAjaxPost(packageSFRequest, sProc, processPackageSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"3\" />";
    callAjaxPost(eventSFRequest, sProc, processEventSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"4\" />";
    callAjaxPost(comboSFRequest, sProc, processComboSFRequestChange);

    var packageNodes = [];
    for (var i=0; i<multiPackageCount; i++) {
        packageNodes.push(multiPackageRequest[i].responseXML.getElementsByTagName('PACKAGE')[0]);
    }

    // get params
    var headerTxt = "";
    var packageNames = [];
    var packageIds = [];
    var multiXML = null;
    var root = multiPackageRequest[0].responseXML.getElementsByTagName('ROOT')[0];
    var listTypes = [];
    for (var i=0; i<multiPackageCount; i++) {
        headerTxt += packageNodes[i].getAttribute('Name');
        if ( (i+1) != multiPackageCount)
            headerTxt += ", ";
        packageNames[i] = packageNodes[i].getAttribute('Name');
        packageIds[i] = packageNodes[i].getAttribute('ID');
        if (i > 0)
            root.appendChild(multiPackageRequest[i].responseXML.getElementsByTagName('PACKAGE')[0]);
        listTypes.push(1);
    }
    multiXML = root;
    
    multiPackageHeader.innerHTML = "Packages: " + headerTxt;
   
    var headerText = packageNames;
    var startTime = new Date(0);
    startTime.setHours(0);
    startTime.setMinutes(0);
    startTime.setSeconds(0);
    var endTime = new Date(0);
    endTime.setHours(0);
    endTime.setMinutes(30);
    endTime.setSeconds(0);
    var listLookupIds = packageIds;
    
    // load and render drag drop editor
    var ddEditor_MultiPackage = new DragDropEditor();
    ddEditor_MultiPackage.load(1, 'multiPackageDDEditorContainer', multiPackageCount, listTypes, headerText, 0, listLookupIds, 
                                startTime, endTime, 15, 1, 880, 18, 55, 15, 5, multiXML);
    ddEditor_MultiPackage.render();
    ddEditor_MultiPackage.activateDD();
    
}

// loads properties and log info
function loadEventPage () {

    // make calls to load search params      
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"3\" />";
    callAjaxPost(eventSFRequest, sProc, processEventSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"4\" />";
    callAjaxPost(comboSFRequest, sProc, processComboSFRequestChange);
    
    if (eventEditorEditChoice == "Edit") {
	    var events = eventRequest.responseXML.getElementsByTagName('EVENT');

	    // set header
	    eventEditorHeader.innerHTML = packageEditorDrillHeader + "Event: " + events[0].getAttribute('Name');
       
       // fill out form        
       $('eventEditor_Name').value = events[0].getAttribute('Name');
       $('eventEditor_Id').value = events[0].getAttribute('ID');
       var duration = parseXMLDate(events[0].getAttribute('Duration'));
       //$('eventEditor_Duration').value = duration[3] + ":" + duration[4] + ":" + duration[5];
       $('eventEditor_Duration').value = duration[4] + ":" + duration[5];
       $('eventEditor_Duration').setAttribute('disabled', 'disabled');
       var startDate = parseXMLDate(events[0].getAttribute('ThisStartDate'));
       if (startDate) $('eventEditor_AirDateFrom').value = startDate[1] + "/" + startDate[2] + "/" + startDate[0].substr(2);
       var endDate = parseXMLDate(events[0].getAttribute('ThisEndDate'));
       if (endDate) $('eventEditor_AirDateTo').value = endDate[1] + "/" + endDate[2] + "/" + endDate[0].substr(2);
       $('eventEditor_Color').style.backgroundColor = "#" + events[0].getAttribute('ThisColor');
       $('eventEditor_CueStringStart').value = events[0].getAttribute('CueStringStart');
       $('eventEditor_CueStringEnd').value = events[0].getAttribute('CueStringEnd');       
           
        // set up params for drag drop editor
        var headerText = ['Mitsubishi','Ribbons','Tickers'];
        var startTime = new Date(0);
        startTime.setHours(0);
        startTime.setMinutes(0);
        startTime.setSeconds(0);
        var endTime = new Date(0);
        endTime.setHours(0);
        endTime.setMinutes(duration[4]);
        endTime.setSeconds(duration[5]);
        var listLookupIds = [1,2,3];  // these are the ids for the channels
        
        // load and render drag drop editor
        var ddEditor_Event = new DragDropEditor();
        ddEditor_Event.load(2, 'eventDDEditorContainer', 3, [1,1,1], headerText, events[0].getAttribute('ID'), listLookupIds, 
                                    startTime, endTime, 5, 1, 880, 18, 55, 15, 5, eventRequest.responseXML);
        ddEditor_Event.render();
        ddEditor_Event.activateDD();
        
        // update day part restrictions
        if (events[0].getAttribute('ThisDayPart')) loadDPR(parseInt(events[0].getAttribute('ThisDayPart'),10));
        
        // load activity log                                 
        var activityLogNodes = eventRequest.responseXML.getElementsByTagName('ACTIVITYLOG');
        loadActivityLog(activityLogNodes, $('eventEditor_Log'), 'Event');
        
    }  else if (eventEditorEditChoice == "New") {
	    // set header
	    eventEditorHeader.innerHTML = packageEditorDrillHeader + "Event: (new event)";
	    $('eventEditor_SaveCopy').setAttribute('disabled', 'disabled');
	    $('eventEditor_Log').style.display = "none";
	    //$('eventEditor_Duration').removeAttribute('disabled');
	    $('eventEditor_Duration').value = "30:00";
	    
	    // set up params for drag drop editor
        var headerText = ['Mitsubishi','Ribbons','Tickers'];
        var startTime = new Date(0);
        startTime.setHours(0);
        startTime.setMinutes(0);
        startTime.setSeconds(0);
        var endTime = new Date(0);
        endTime.setHours(0);
        endTime.setMinutes(30);
        endTime.setSeconds(0);
        var listLookupIds = [1,2,3];  // these are the ids for the channels
	    
	    // load and render drag drop editor
        var ddEditor_Event = new DragDropEditor();
        ddEditor_Event.load(2, 'eventDDEditorContainer', 3, [1,1,1], headerText, -1, listLookupIds, 
                                    startTime, endTime, 5, 1, 880, 18, 55, 15, 5, eventRequest.responseXML);
        ddEditor_Event.render();
        ddEditor_Event.activateDD();
	}
	
	// render meta-data fields
    renderMetaData(eventRequest.responseXML);
    // load meta-data fields
    loadMDValues(eventRequest.responseXML, 'eventEditorMetaData');
    
    $('pageContainer').removeClassName('fadedBG');
    $('loadingMsg').style.display = "none";    
}

// combo editor
var dataTagRuleIndex = 0;
var prevComboDuration = "";
var prevComboChannelIndex = 0;
// loads properties and log info
function loadComboPage () {
		
    // make calls to load search params   
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"4\" />";
    callAjaxPost(comboSFRequest, sProc, processComboSFRequestChange);
    		
    // populate channel drop down
    var channels = comboRequest.responseXML.getElementsByTagName('CHANNEL');
    var channelSelect = $('comboEditor_Channel');
    if (channelSelect.options.length == 1) {
        for (var i=0, len=channels.length; i<len; i++) {
            var optionEl = document.createElement('option');
            optionEl.text = channels[i].getAttribute('Name');
            optionEl.value = channels[i].getAttribute('ID');
            channelSelect.options.add(optionEl);
        }    		
    }
    // populate video source drop down
//    var sources = comboRequest.responseXML.getElementsByTagName('VIDEOSOURCE');
//    var sourceSelect = $('comboEditor_VideoSource');
//    for (var i=0, len=sources.length; i<len; i++) {
//        var optionEl = document.createElement('option');
//        optionEl.text = sources[i].getAttribute('Name');
//        optionEl.value = sources[i].getAttribute('CueString');
//        sourceSelect.options.add(optionEl);
//    }
    		
	if ( (comboEditorEditChoice == "Edit") || (comboEditorEditChoice == "EditDefault") ) {
	    var combos = comboRequest.responseXML.getElementsByTagName('ASSET');
	    	          	 
	    // set header
	    comboEditorHeader.innerHTML = eventEditorDrillHeader + "Combo: " + combos[0].getAttribute('Name');
       
       // fill out form        
       $('comboEditor_Name').value = combos[0].getAttribute('Name');
       $('comboEditor_Id').value = combos[0].getAttribute('ID');
       var channels = (combos[0].getAttribute('ChannelsNN')) ? combos[0].getAttribute('ChannelsNN').split(',') : null;
       if (channels) {
            var channelOptions = channelSelect.immediateDescendants();
            for (var i=0, len=channelOptions.length; i<len; i++) {
                if (channelOptions[i].value == channels[1]) {
                    channelOptions[i].selected = true;
                } else {
                    channelOptions[i].selected = false;
                }
            }
            //$('comboEditor_Channel').selectedIndex = channels[1];
            prevComboChannelIndex = channelSelect.selectedIndex;
       }
       $('comboEditor_Channel').setAttribute('disabled', 'disabled');
       $('comboEditor_Channel').className = "disabledSelect";
       var duration = parseXMLDate(combos[0].getAttribute('Duration'));
       //$('comboEditor_Duration').value = duration[3] + ":" + duration[4] + ":" + duration[5];
       $('comboEditor_Duration').value = duration[4] + ":" + duration[5];
       prevComboDuration = $('comboEditor_Duration').value;
       $('comboEditor_Duration').setAttribute('disabled', 'disabled');
       var startDate = parseXMLDate(combos[0].getAttribute('ThisStartDate'));
       if (startDate) $('comboEditor_AirDateFrom').value = startDate[1] + "/" + startDate[2] + "/" + startDate[0].substr(2);
       var endDate = parseXMLDate(combos[0].getAttribute('ThisEndDate'));
       if (endDate) $('comboEditor_AirDateTo').value = endDate[1] + "/" + endDate[2] + "/" + endDate[0].substr(2);
       $('comboEditor_Color').style.backgroundColor = "#" + combos[0].getAttribute('ThisColor');
       
       // after channel is selected update list of video sources
       updateVideoSources();
       
       // parse out video source from cue string
       var sources = comboRequest.responseXML.getElementsByTagName('VIDEOSOURCE');
       var sourceSelect = $('comboEditor_VideoSource');
       var cueStringStart = combos[0].getAttribute('CueStringStart');
       if (cueStringStart) {
           var videoSource = cueStringStart.split(',')[0];
           //if (videoSource.length != cueStringStart.length) {
           if (videoSource.length > 0) {
                // check to see if this is a video source
                var sourceOptions = sourceSelect.immediateDescendants();
                var validSource = false;
                for (var i=0, len=sourceOptions.length; i<len; i++) {
                    if (sourceOptions[i].value == videoSource) {
                        sourceOptions[i].selected = true;
                        validSource = true;
                    } else {
                        sourceOptions[i].selected = false;
                    }
                }
                if (validSource) {
                    // remove video source from cue string
                    cueStringStart = cueStringStart.substr(videoSource.length+1);
                }
           }
       }
       
       $('comboEditor_CueStringStart').value = cueStringStart;
       $('comboEditor_CueStringEnd').value = combos[0].getAttribute('CueStringEnd');      
           
        // default combo
        var defaultCombo = comboRequest.responseXML.getElementsByTagName('DEFAULTCOMBO');
        if (defaultCombo.length > 0) {
            $('comboEditor_DefaultCombo').checked = true;   
            $('comboEditor_DefaultCombo').setAttribute('disabled','disabled');
        }
           
        // set up params for drag drop editor
        var headerText = [];
        var startTime = new Date(0);
        startTime.setHours(0);
        startTime.setMinutes(0);
        startTime.setSeconds(0);
        var endTime = new Date(0);
        endTime.setHours(0);
        endTime.setMinutes(duration[4]);
        endTime.setSeconds(duration[5]);
        var listLookupIds = [];  // these are the ids for the channels
        
        // load and render drag drop editor
        var ddEditor_Combo = new DragDropEditor();
        ddEditor_Combo.load(3, 'comboEditor_Assets', 0, null, null, combos[0].getAttribute('ID'), null, 
                                    startTime, endTime, -1, -1, -1, -1, -1, -1, -1, comboRequest.responseXML);
                         
        // update day part restrictions
        if (combos[0].getAttribute('ThisDayPart')) loadDPR(parseInt(combos[0].getAttribute('ThisDayPart'),10));
        
        // load activity log                                 
        var activityLogNodes = comboRequest.responseXML.getElementsByTagName('ACTIVITYLOG');
        loadActivityLog(activityLogNodes, $('comboEditor_Log'), 'Combo');
        
	} else if (comboEditorEditChoice == "New") {
	    // set header
	    comboEditorHeader.innerHTML = eventEditorDrillHeader + "Combo: (new combo)";
	    $('comboEditor_SaveCopy').setAttribute('disabled', 'disabled');
	    $('comboEditor_Log').style.display = "none";
	    $('comboEditor_Duration').removeAttribute('disabled');
	    
	    // load and render drag drop editor
        var ddEditor_Combo = new DragDropEditor();
        ddEditor_Combo.load(3, 'comboEditor_Assets', 0, null, null, -1, null, 
                                    null, null, -1, -1, -1, -1, -1, -1, -1, comboRequest.responseXML);
                                    
	}
	
	// show or hide assets and templates based on duration and channel
    checkComboOptions();
	
	// render meta-data fields
    renderMetaData(comboRequest.responseXML);
    // load meta-data fields
    loadMDValues(comboRequest.responseXML, 'comboEditorMetaData');
	
	// add drop to default asset
	var defaultAsset = $('comboEditorDefaultAsset');
	addDrop(defaultAsset);
	
	// assign drag container
	activeEditor.dragContainer = $('comboEditorAssetIcon');    
	                                       
    $('pageContainer').removeClassName('fadedBG');
    $('loadingMsg').style.display = "none";
    
    comboEditorLoaded = true;
    updateComboSFOptions();
}

// loads properties and log info
function loadAssetPage () {
    // assign values from global config
    var cfg = assetRequest.responseXML.getElementsByTagName('GLOBALCONFIG');
    for (var i=0, len=cfg.length; i<len; i++) {
        if (cfg[i].getAttribute('Property') == 'AssetThumbnailVidPath')
            assetThumbnailVidPathCfg = cfg[i].getAttribute('Value');
        if (cfg[i].getAttribute('Property') == 'AssetThumbnailVidSize')
            assetThumbnailVidSizeCfg = cfg[i].getAttribute('Value');
        if (cfg[i].getAttribute('Property') == 'AssetThumbnailJPEGPath')
            assetThumbnailJPEGPathCfg = cfg[i].getAttribute('Value');
        if (cfg[i].getAttribute('Property') == 'AssetThumbnailJPEGSize')
            assetThumbnailJPEGSizeCfg = cfg[i].getAttribute('Value');
    }

    // populate channel drop down
    var channels = assetRequest.responseXML.getElementsByTagName('CHANNEL');
    var channelSelect = $('assetEditor_Channel');
    for (var i=0, len=channels.length; i<len; i++) {
        var optionEl = document.createElement('option');
        optionEl.text = channels[i].getAttribute('Name');
        optionEl.value = channels[i].getAttribute('ID');
        channelSelect.options.add(optionEl);
    }  
    	        
    // populate user "assign to" drop-down
    var users = assetRequest.responseXML.getElementsByTagName('USER');
    var userSelect = $('assetEditor_TaskAssignTo');
    for (var i=0, len=users.length; i<len; i++) {
        if (users[i].parentNode.nodeName == 'ACTIVITYLOG') continue;
        var optionEl = document.createElement('option');
        optionEl.text = users[i].getAttribute('UserName');
        optionEl.value = users[i].getAttribute('ID');
        userSelect.options.add(optionEl);
    }
    // populate task type drop-down
    var taskOptions = assetRequest.responseXML.getElementsByTagName('TASKOPTION');
    var taskOptionSelect = $('assetEditor_TaskType');
    for (var i=0, len=taskOptions.length; i<len; i++) {
        var optionEl = document.createElement('option');
        optionEl.text = taskOptions[i].getAttribute('Name');
        optionEl.value = taskOptions[i].getAttribute('ID');
        taskOptionSelect.options.add(optionEl);
    }

	if (assetEditorEditChoice == "Edit") {
	    var assets = assetRequest.responseXML.getElementsByTagName('ASSET');
    	
        // alert if any media in mediainstanceupdate
        if (assets[0].getElementsByTagName('MEDIAINSTANCEUPDATE').length > 0) {
            var spanTxt = "<span style='font-weight:bold;'>Warning</span>";
            var lblTxt = "This asset contains media ready for update.  Please check the asset capture application to confirm.";
            var onClickOK = "hideAlertPopup();"
            $('alertHeader').style.backgroundColor = "Red";
            showAlertPopup(spanTxt, lblTxt, onClickOK);  	
        }
    	
	    // set header
	    if (assetEditorReturnChoice == "Events") {
            assetEditorHeader.innerHTML = eventEditorDrillHeader + "Asset: " + assets[0].getAttribute('Name');
        } else {
            assetEditorHeader.innerHTML = comboEditorDrillHeader + "Asset: " + assets[0].getAttribute('Name');
        }

       $('assetEditor_Name').value = assets[0].getAttribute('Name');
       $('assetEditor_Id').value = assets[0].getAttribute('ID');
       var channels = (assets[0].getAttribute('ChannelsNN')) ? assets[0].getAttribute('ChannelsNN').split(',') : null;
       if (channels) {
            var channelOptions = channelSelect.immediateDescendants();
            for (var i=0, len=channelOptions.length; i<len; i++) {
                if (channelOptions[i].value == channels[1]) {
                    channelOptions[i].selected = true;
                } else {
                    channelOptions[i].selected = false;
                }
            }
       }
       $('assetEditor_Channel').setAttribute('disabled', 'disabled');
       $('assetEditor_Channel').className = "disabledSelect";
       var duration = parseXMLDate(assets[0].getAttribute('Duration'));
       $('assetEditor_Duration').value = duration[4] + ":" + duration[5];
       $('assetEditor_Duration').setAttribute('disabled', 'disabled');
       var startDate = parseXMLDate(assets[0].getAttribute('ThisStartDate'));
       if (startDate) $('assetEditor_AirDateFrom').value = startDate[1] + "/" + startDate[2] + "/" + startDate[0].substr(2);
       var endDate = parseXMLDate(assets[0].getAttribute('ThisEndDate'));
       if (endDate) $('assetEditor_AirDateTo').value = endDate[1] + "/" + endDate[2] + "/" + endDate[0].substr(2);
       $('assetEditor_Color').style.backgroundColor = "#" + assets[0].getAttribute('ThisColor');
       
       // after channel is selected update list of video sources
       updateVideoSources();
       
       // parse out video source from cue string
       var sources = assetRequest.responseXML.getElementsByTagName('VIDEOSOURCE');
       var sourceSelect = $('assetEditor_VideoSource');
       var cueStringStart = assets[0].getAttribute('CueStringStart');
       if (cueStringStart) {
           var videoSource = cueStringStart.split(',')[0];
           //if (videoSource.length != cueStringStart.length) {
           if (videoSource.length > 0) {
                // check to see if this is a video source
                var sourceOptions = sourceSelect.immediateDescendants();
                var validSource = false;
                for (var i=0, len=sourceOptions.length; i<len; i++) {
                    if (sourceOptions[i].value == videoSource) {
                        sourceOptions[i].selected = true;
                        validSource = true;
                    } else {
                        sourceOptions[i].selected = false;
                    }
                }
                if (validSource) {
                    // remove video source from cue string
                    cueStringStart = cueStringStart.substr(videoSource.length+1);
                }
           }
       }
     
       $('assetEditor_CueStringStart').value = cueStringStart;
       $('assetEditor_CueStringEnd').value = assets[0].getAttribute('CueStringEnd');

        // load tasks
        var tasks = assetRequest.responseXML.getElementsByTagName('TASK');
        var listBox = $('assetEditor_Tasks');
        for (var i=0, len=tasks.length; i<len; i++) {
            var optionEl = document.createElement('option');
            var taskOption = getItemById(tasks[i].getAttribute('TaskOptionID'), taskOptions);
            var taskUser = getUserById(tasks[i].getAttribute('UserID'), users);
            optionEl.text = taskOption.getAttribute('Name') + " (" + taskUser.getAttribute('UserName') + ")";
            optionEl.value = tasks[i].getAttribute('ID');
            //optionEl.value = parseInt(i,10) + 1;  // task ids are re-created with each save
            listBox.options.add(optionEl);
        }
        listBox.selectedIndex = -1;

        // set up params for drag drop editor
        var startTime = new Date(0);
        startTime.setHours(0);
        startTime.setMinutes(0);
        startTime.setSeconds(0);
        var endTime = new Date(0);
        endTime.setHours(0);
        endTime.setMinutes(duration[4]);
        endTime.setSeconds(duration[5]);
        
        // load and render drag drop editor - only necessary for drill down
        var ddEditor_Asset = new DragDropEditor();
        ddEditor_Asset.load(4, null, 0, null, null, assets[0].getAttribute('ID'), null, 
                                    startTime, endTime, -1, -1, -1, -1, -1, -1, -1, assetRequest.responseXML);
                                    
        // update day part restrictions
        if (assets[0].getAttribute('ThisDayPart')) loadDPR(parseInt(assets[0].getAttribute('ThisDayPart'),10));
        
        // load activity log                                 
        var activityLogNodes = assetRequest.responseXML.getElementsByTagName('ACTIVITYLOG');
        loadActivityLog(activityLogNodes, $('assetEditor_Log'), 'Asset');
        
	} else if (assetEditorEditChoice == "New") {
	    // set header
	    if (assetEditorReturnChoice == "Events") {
            assetEditorHeader.innerHTML = eventEditorDrillHeader + "Asset: (new asset)";
        } else {
            assetEditorHeader.innerHTML = comboEditorDrillHeader + "Asset: (new asset)";
        }

	    $('assetEditor_SaveCopy').setAttribute('disabled', 'disabled');
	    $('assetEditor_Log').style.display = "none";
	    $('assetEditor_Duration').removeAttribute('disabled');
	    // load and render drag drop editor
        var ddEditor_Asset = new DragDropEditor();
        ddEditor_Asset.load(4, null, -1, null, null, -1, null, 
                                    null, null, -1, -1, -1, -1, -1, -1, -1, assetRequest.responseXML);
	}
	
	// show files based on channel selection
    updateAssetFiles();
    // render meta-data fields
    renderMetaData(assetRequest.responseXML);
    // load meta-data fields
    loadMDValues(assetRequest.responseXML, 'assetEditorMetaData');
                                        
    $('pageContainer').removeClassName('fadedBG');
    $('loadingMsg').style.display = "none";	
}

// function to reset package page 
function resetPackagePage() {
    // remove search fields
    var sfOptions = $('packageEditor_SearchFields').immediateDescendants();
    for (var i=0, len=sfOptions.length; i<len; i++) {
        sfOptions[i].remove();
    }
    
    // hide search field buttons
    $('eventSearchButtons').style.display = "none";
    
    // reset header
    packageEditorHeader.innerHTML = "";
    
    // hide messages
    $('packageEditor_Messages').style.display = "none"; 
    
    // reset static fields
    $('packageEditor_Name').value = "";
    $('packageEditor_Id').value = "";
    $('packageEditor_Duration').value = "";
    $('packageEditor_Duration').removeAttribute('disabled');
    $('packageEditor_AirDateFrom').value = "";
    $('packageEditor_AirDateTo').value = "";
    $('packageEditor_Color').style.backgroundColor = "#3399FF";
    $('packageEditor_CueStringStart').value = "";
    $('packageEditor_CueStringEnd').value = "";
    
    // remove meta data fields
    var mdFields = $('packageEditorMetaData').immediateDescendants();
    for (var i=0, len=mdFields.length; i<len; i++) {
        mdFields[i].remove();
    }
       
    // remove cue strings
    var cueStrings = $('packageEditorCues').immediateDescendants();
    for (var i=0, len=cueStrings.length; i<len; i++) {
        cueStrings[i].remove();
    }
    
    // update day part
    checkDayPart('all');
    
    // clear globals
    packageEditorPackageDate = "";
    packageEditorPackageTime = "";
    packageEditorPecaEl = null;
    
    // clear log
    $('packageEditor_Log').value = "";
}

// function to reset event page 
function resetEventPage() {
    // remove search fields
    var sfOptions = $('eventEditor_SearchFields').immediateDescendants();
    for (var i=0, len=sfOptions.length; i<len; i++) {
        sfOptions[i].remove();
    }
    
    // hide search field buttons
    $('comboSearchButtons').style.display = "none";
    
    // reset header
    eventEditorHeader.innerHTML = "";
    
    // hide messages
    $('eventEditor_Messages').style.display = "none"; 
    
    // reset static fields
    $('eventEditor_Name').value = "";
    $('eventEditor_Id').value = "";
    $('eventEditor_Duration').value = "";
    //$('eventEditor_Duration').removeAttribute('disabled');
    $('eventEditor_AirDateFrom').value = "";
    $('eventEditor_AirDateTo').value = "";
    $('eventEditor_Color').style.backgroundColor = "#3399FF";
    $('eventEditor_CueStringStart').value = "";
    $('eventEditor_CueStringEnd').value = "";
    
    // remove meta data fields
    var mdFields = $('eventEditorMetaData').immediateDescendants();
    for (var i=0, len=mdFields.length; i<len; i++) {
        mdFields[i].remove();
    }
       
    // remove cue strings
    var cueStrings = $('eventEditorCues').immediateDescendants();
    for (var i=0, len=cueStrings.length; i<len; i++) {
        cueStrings[i].remove();
    }
    
    // update day part
    checkDayPart('all');
    
    // clear log
    $('eventEditor_Log').value = "";
    
    // reset global
    eventEditorDurationUpdated = false;
}

// function to reset combo page 
function resetComboPage() {
    // remove search fields
    var sfOptions = $('comboEditor_SearchFields').immediateDescendants();
    for (var i=0, len=sfOptions.length; i<len; i++) {
        sfOptions[i].remove();
    }
    
    // hide search field buttons
    $('assetSearchButtons').style.display = "none";
    
    // reset header
    comboEditorHeader.innerHTML = "";
    
    // hide messages
    $('comboEditor_Messages').style.display = "none"; 
    $('dataTagAlerts').style.display = "none";
       
    // reset static fields
    $('comboEditor_Name').value = "";
    $('comboEditor_Id').value = "";
    $('comboEditor_Channel').selectedIndex = 0;  // clear channels on load
    $('comboEditor_Channel').removeAttribute('disabled');
    $('comboEditor_Channel').className = "widthM";
    $('comboEditor_Duration').value = "";
    $('comboEditor_Duration').removeAttribute('disabled');
    $('comboEditor_AirDateFrom').value = "";
    $('comboEditor_AirDateTo').value = "";
    $('comboEditor_Color').style.backgroundColor = "#3399FF";
    $('comboEditor_CueStringStart').value = "";
    $('comboEditor_CueStringEnd').value = "";
    
    $('comboEditor_VideoSource').selectedIndex = 0;
//    var sourceOptions = $('comboEditor_VideoSource').immediateDescendants();
//    for (var i=0, len=sourceOptions.length; i<len; i++) {
//        sourceOptions[i].remove();
//    }
    
    $('comboEditor_DefaultCombo').checked = false;
    $('comboEditor_DefaultCombo').removeAttribute('disabled');
    
    // reset global duration and channel
    prevComboDuration = ""; 
    prevComboChannelIndex = 0;
    
    // remove meta data fields
    var mdFields = $('comboEditorMetaData').immediateDescendants();
    for (var i=0, len=mdFields.length; i<len; i++) {
        mdFields[i].remove();
    }
    
    // remove asset and tag associations
    // remove item from drag container if exists
    var dragContainer = $('comboEditorAssetIcon');   
	if (dragContainer.firstDescendant()) dragContainer.firstDescendant().remove();
	// remove default asset if exists
	var defaultAsset = $('comboEditorDefaultAsset');
	if (defaultAsset.firstDescendant()) defaultAsset.firstDescendant().remove();
	// remove data rules
    var dataTagRules = $('comboEditor_DataTagRulesContainer').immediateDescendants();
    for (var i=0, len=dataTagRules.length; i<len; i++) {
        dataTagRules[i].remove();
    }
    
    // remove template options
    var templateSelectOptions = $('comboEditorTemplateSelect').immediateDescendants();
    for (var i=1, len=templateSelectOptions.length; i<len; i++) {
        templateSelectOptions[i].remove();
    }
    
    // remove text string boxes - !!! Enhance
    var tickerEditors = $('comboEditorTextStrings').immediateDescendants();
    for (var i=0, len=tickerEditors.length; i<len; i++) {
        tickerEditors[i].remove();
    }
    
    // update panels to show default
    checkComboOptions();
    
    // update day part
    checkDayPart('all');
    
    // clear log
    $('comboEditor_Log').value = "";
    
    // reset loaded globals
    comboEditorSFLoaded = false;
    comboEditorLoaded = false;
}

// function to reset asset page 
function resetAssetPage() {
    // reset xml
    // not necessary
    
    // reset header
    assetEditorHeader.innerHTML = "";
    
    // hide search field buttons
    //$('mediaSearchButtons').style.display = "none";
    
    // hide messages
    $('assetEditor_Messages').style.display = "none"; 
    $('assetEditor_TaskMessages').style.display = "none"; 
    
    // update files - must do this before clearing channel
    $('assetEditor_Channel').selectedIndex = 0;
    removeFileFromAsset(1);
    removeFileFromAsset(2);
    updateAssetFiles(); 
    
    // reset static fields
    $('assetEditor_Name').value = "";
    $('assetEditor_Id').value = "";
    $('assetEditor_Color').style.backgroundColor = "#3399ff";
    
    var channelOptions = $('assetEditor_Channel').immediateDescendants();
    for (var i=1, len=channelOptions.length; i<len; i++) {
        channelOptions[i].remove();
    }
    $('assetEditor_Channel').removeAttribute('disabled');
    $('assetEditor_Channel').className = "widthM";
    
    $('assetEditor_Duration').value = "";
    $('assetEditor_Duration').removeAttribute('disabled');
    $('assetEditor_AirDateFrom').value = "";
    $('assetEditor_AirDateTo').value = "";
    $('assetEditor_Color').style.backgroundColor = "#3399FF";
    $('assetEditor_CueStringStart').value = "";
    $('assetEditor_CueStringEnd').value = "";
    
    $('assetEditor_VideoSource').selectedIndex = 0;
//    var sourceOptions = $('assetEditor_VideoSource').immediateDescendants();
//    for (var i=0, len=sourceOptions.length; i<len; i++) {
//        sourceOptions[i].remove();
//    }
    
    // remove meta data fields
    var mdFields = $('assetEditorMetaData').immediateDescendants();
    for (var i=0, len=mdFields.length; i<len; i++) {
        mdFields[i].remove();
    }
    
    // reset task fields
    resetTaskFields();
    var taskListOptions = $('assetEditor_Tasks').immediateDescendants();
    var taskUserListOptions = $('assetEditor_TaskAssignTo').immediateDescendants();
    var taskTypeListOptions = $('assetEditor_TaskType').immediateDescendants();
    for (var i=0, len=taskListOptions.length; i<len; i++) {
        taskListOptions[i].remove();
    }
    for (var i=1, len=taskUserListOptions.length; i<len; i++) {
        taskUserListOptions[i].remove();
    }
    for (var i=1, len=taskTypeListOptions.length; i<len; i++) {
        taskTypeListOptions[i].remove();
    }      
    
    // update day part
    checkDayPart('all');
    
    // clear log
    $('assetEditor_Log').value = "";
    
    // reset return choice
    assetEditorReturnChoice = "";
}

function loadLiveControlEventSearch() {
    searchChoice = "Event";
    var searchFields = $('liveControl_PackageSearchFields').immediateDescendants();
    for (var i=0, len=searchFields.length; i<len; i++) {
        searchFields[i].remove();
    }
    $('liveControlPackageSearchLink').style.display = "block";
    $('liveControlEventSearchLink').style.display = "none";
    $('liveControlPackageResultsBox').style.display = "none";
    $('liveControlEventResultsBox').style.display = "block";
    $('packageSearchButtons').style.display = "none";
    
    // make calls to load search params   
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"2\" />";
    callAjaxPost(packageSFRequest, sProc, processPackageSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"3\" />";
    callAjaxPost(eventSFRequest, sProc, processEventSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"4\" />";
    callAjaxPost(comboSFRequest, sProc, processComboSFRequestChange);
}

function loadLiveControlPackageSearch() {
    searchChoice = "Package";
    var searchFields = $('liveControl_EventSearchFields').immediateDescendants();
    for (var i=0, len=searchFields.length; i<len; i++) {
        searchFields[i].remove();
    }
    $('liveControlPackageSearchLink').style.display = "none";
    $('liveControlEventSearchLink').style.display = "block";
    $('liveControlPackageResultsBox').style.display = "block";
    $('liveControlEventResultsBox').style.display = "none";
    $('eventSearchButtons').style.display = "none";
    
    // make calls to load search params   
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"1\" />";
    callAjaxPost(scheduleSFRequest, sProc, processScheduleSFRequestChange);
    
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"2\" />";
    callAjaxPost(packageSFRequest, sProc, processPackageSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"3\" />";
    callAjaxPost(eventSFRequest, sProc, processEventSFRequestChange);
    
    sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetSearchFields\" Level=\"4\" />";
    callAjaxPost(comboSFRequest, sProc, processComboSFRequestChange);
}

function liveControlPackageIndexChange() {
    $('liveControlPackageLoad').removeAttribute('disabled'); 
    var listBox = $('liveControlPackageResults');
    activeEditor.updateGetInfo(listBox.options[listBox.selectedIndex].value);
}

var sfXML = null;
var scheduleSFXML = null;
var packageSFXML = null;
var eventSFXML = null;
var comboSFXML = null;
var assetSFXML = null;
// function to load search fields for an editor
function loadSearchFields() {
    var level = 0;
    if (activeEditorPageId == "scheduleEditor" || activeEditorPageId == "packageList") {
        level = 1;
    } else if (activeEditorPageId == "packageEditor" || activeEditorPageId == "eventList") {
        level = 2;
    } else if (activeEditorPageId == "eventEditor" || activeEditorPageId == "comboList") {
        level = 3;
    } else if (activeEditorPageId == "comboEditor" || activeEditorPageId == "assetList") {
        level = 4;
    } else if (activeEditorPageId == "liveControl") {
        level = (searchChoice == "Package") ? 1 : 2;
    } else if (activeEditorPageId.match('report')) {
        level = 4;
    } else if (activeEditorPageId.match('multiPackage')) {
        level = 2;
    }
    
    
    
    // return if not all requests are complete
    for (var i=level; i<=4; i++) {
        if (loadedSearchFields[i] == 0) return;
    }
    
    var container = null;    
    var nameAtt = null;
    var disabledAtt = null;
    if (level == 1) {
        if (activeEditorPageId != "liveControl") {
            container = (activeEditorPageId == "scheduleEditor") ? $('scheduleEditor_SearchFields') : $('packageList_SearchFields');
        } else {
            container = $('liveControl_PackageSearchFields');
        }
        scheduleSFXML = scheduleSFRequest.responseXML;
        var root = scheduleSFXML.getElementsByTagName('AllSearchFields')[0];
        root.appendChild(packageSFRequest.responseXML.getElementsByTagName('SearchFields')[0]);
        root.appendChild(eventSFRequest.responseXML.getElementsByTagName('SearchFields')[0]);
        root.appendChild(comboSFRequest.responseXML.getElementsByTagName('SearchFields')[0]); 
        // assign value for stored procedure
        nameAtt = scheduleSFXML.createAttribute('Name');
        nameAtt.value = "sproc_WEB_GetListPackage";
        disabledAtt = scheduleSFXML.createAttribute('IncludeDisabled');
        disabledAtt.value = "false";
        sfXML = scheduleSFXML;
    } else if (level == 2) {
        if (activeEditorPageId == "liveControl")  {
            container = $('liveControl_EventSearchFields');
        } else if (activeEditorPageId == "multiPackage")  {
            container = $('multiPackage_SearchFields');
        } else {
            container = (activeEditorPageId == "packageEditor") ? $('packageEditor_SearchFields') : $('eventList_SearchFields');
        }
        packageSFXML = packageSFRequest.responseXML;
        var root = packageSFXML.getElementsByTagName('AllSearchFields')[0];
        root.appendChild(eventSFRequest.responseXML.getElementsByTagName('SearchFields')[0]);
        root.appendChild(comboSFRequest.responseXML.getElementsByTagName('SearchFields')[0]);
        // assign value for stored procedure
        nameAtt = packageSFXML.createAttribute('Name');
        nameAtt.value = "sproc_WEB_GetListEvent";
        disabledAtt = packageSFXML.createAttribute('IncludeDisabled');
        disabledAtt.value = "false";
        sfXML = packageSFXML;
    } else if (level == 3) {
        container = (activeEditorPageId == "eventEditor") ? $('eventEditor_SearchFields') : $('comboList_SearchFields');
        eventSFXML = eventSFRequest.responseXML;
        var root = eventSFXML.getElementsByTagName('AllSearchFields')[0];
        root.appendChild(comboSFRequest.responseXML.getElementsByTagName('SearchFields')[0]);
        // assign value for stored procedure
        nameAtt = eventSFXML.createAttribute('Name');
        nameAtt.value = "sproc_WEB_GetListCombo";
        disabledAtt = eventSFXML.createAttribute('IncludeDisabled');
        disabledAtt.value = "false";
        sfXML = eventSFXML;
    } else if (level == 4) {
        if (!activeEditorPageId.match('report')) {
            container = (activeEditorPageId == "comboEditor") ? $('comboEditor_SearchFields') : $('assetList_SearchFields');
        } else {
            container = $('assetSearchFields');
        }
        comboSFXML = comboSFRequest.responseXML;
        // assign value for stored procedure
        nameAtt = comboSFXML.createAttribute('Name');
        nameAtt.value = "sproc_WEB_GetListAsset";
        disabledAtt = comboSFXML.createAttribute('IncludeDisabled');
        disabledAtt.value = "false";
        sfXML = comboSFXML;
    }
   
    // add element node for stored procedure
    var sProcEl = sfXML.createElement('STOREDPROCEDURE');
    sProcEl.setAttributeNode(nameAtt);
    sProcEl.setAttributeNode(disabledAtt);
    var firstSFNode = sfXML.getElementsByTagName('SearchFields')[0];
    var xDoc = sfXML.documentElement;  // documentElement simply gets the root node
    xDoc.insertBefore(sProcEl, firstSFNode);

    // reset loadedsearchfield array
    for (var i=level; i<=4; i++) {
        loadedSearchFields[i] = 0;
    }

    var searchFields = sfXML.getElementsByTagName('SearchFields');
    for (var i=0, len=searchFields.length; i<len; i++) {
        var subFieldLists = [];
        var subFieldNodes = [];
        var fieldNodes = [];
        var searchFieldChildren = searchFields[i].childNodes;
        for (j=0, jlen=searchFieldChildren.length; j<jlen; j++) {
            if (searchFieldChildren[j].tagName == "Field") {
                fieldNodes.push(searchFieldChildren[j]);
            }
        }
        
        var rows = [];
        var cols = [];
        var labels = [];
        var fields = [];
        var rowIndex = 0;
        var skipped = 0;
        for (var j=0, jlen=fieldNodes.length; j<jlen; j++) {
                    
            var fieldName = fieldNodes[j].getAttribute('Name');
            
            if (!fieldName) {
                skipped++;
                continue;
            }
            
            // skip second field of time or date
            if (fieldName.split('.')[1] == 'End') {
                skipped++;
                continue;
            }
            
            var fieldLabel = document.createElement('label');
            fieldLabel.innerHTML = fieldName;
            
            var fieldType = fieldNodes[j].getAttribute('DataType');
            
            var field = document.createElement('div');
            field.style.float = "left";
            if ( (fieldType == 'int') || (fieldType == 'decimal') || (fieldType.match('varchar')) ) {
                var fieldEl = document.createElement('input');
                fieldEl.setAttribute('type','text');
                fieldEl.style.width = "85px";
                fieldEl.id = "Level_" + (level+i) + "_Name_" + fieldName;
                fieldEl.setAttribute('onfocus','cs_blur();');
                field.appendChild(fieldLabel);
                field.appendChild(fieldEl);
            } else if (fieldType == 'date') {
                var dateFrom = document.createElement('input');
                dateFrom.setAttribute('type','text');
                dateFrom.className = "date";
                dateFrom.style.width = "33px";
                dateFrom.setAttribute('onfocus','this.select();lcs(this);');
                dateFrom.setAttribute('onclick','event.cancelBubble=true;this.select();lcs(this);');
                var fieldNameBase = fieldName.split('.')[0];
                dateFrom.id = "Level_" + (level+i) + "_Name_" + fieldNameBase + ".Start";
                var span = document.createElement('span');
                span.innerHTML = "to";
                var dateTo = document.createElement('input');
                dateTo.setAttribute('type','text');
                dateTo.className = "date";
                dateTo.style.width = "33px";
                dateTo.setAttribute('onfocus','this.select();lcs(this);');
                dateTo.setAttribute('onclick','event.cancelBubble=true;this.select();lcs(this);');
                dateTo.id = "Level_" + (level+i) + "_Name_" + fieldNameBase + ".End";
                fieldLabel.innerHTML = fieldNameBase;
                field.appendChild(fieldLabel);
                field.appendChild(dateFrom);
                field.appendChild(span);
                field.appendChild(dateTo);
            }  else if (fieldType == 'time') {
                var timeFrom = document.createElement('input');
                timeFrom.setAttribute('type','text');
                timeFrom.className = "date";
                timeFrom.style.width = "33px";
                var fieldNameBase = fieldName.split('.')[0];
                timeFrom.id = "Level_" + (level+i) + "_Name_" + fieldNameBase + ".Start";
                var span = document.createElement('span');
                span.innerHTML = "to";
                var timeTo = document.createElement('input');
                timeTo.setAttribute('type','text');
                timeTo.className = "date";
                timeTo.style.width = "33px";
                timeTo.id = "Level_" + (level+i) + "_Name_" + fieldNameBase + ".End";
                fieldLabel.innerHTML = fieldNameBase + " (mm:ss)";
                field.appendChild(fieldLabel);
                field.appendChild(timeFrom);
                field.appendChild(span);
                field.appendChild(timeTo);
            } else if (fieldType == 'list') {
                var fieldSelect = document.createElement('select');
                fieldSelect.style.width = "205px"
                fieldSelect.setAttribute('onfocus','cs_blur();');
                fieldSelect.id = "Level_" + (level+i) + "_Name_" + fieldName;
                // get options for this list
                var listOptions = [];
                var fieldChildren = fieldNodes[j].childNodes;
                for (k=0, klen=fieldChildren.length; k<klen; k++) {
                    if (fieldChildren[k].tagName == "Option") {
                        listOptions.push(fieldChildren[k]);
                    }
                }
                
                // create default option
                var optionEl = document.createElement('option');
                optionEl.value = "-1";
                optionEl.text = "Select...";
                fieldSelect.options.add(optionEl);
                for (var k=0, klen=listOptions.length; k<klen; k++) {
                    var optionEl = document.createElement('option');
                    optionEl.value = listOptions[k].getAttribute('ID');
                    optionEl.text = listOptions[k].getAttribute('Name');
                    fieldSelect.options.add(optionEl);
                } 
                field.appendChild(fieldLabel);
                field.appendChild(fieldSelect);
                
                // increment skipped
                skipped++
                
                // determine if this is a sub list - must do after rendering
                var subOfField = fieldNodes[j].getAttribute('SubOfField');
                if (subOfField != '') {
                    fieldSelect.setAttribute('onchange', 'updateSFMDOptions(this, ' + (level+i) + ', ' + '\"' + subOfField + '\");');
                }                
            }
            
            var index = (j+skipped)%2;
            fields[index] = field;
            
            if (fields[index]  && fieldType != 'list') {
                var col = document.createElement('col');
                col.className = ( (index) == 0 ) ? "col" : "col right";
                cols[index] = col;
                cols[index].appendChild(fields[index]);
            } else {
                var col = document.createElement('col');
                col.className = "col";
                cols[0] = col;
                cols[0].appendChild(fields[index]);
            }
        
            if ( ( index == 1 || j == (jlen-1) || ( j == (jlen-2) && fieldName.split('.')[1] == 'Start' && index == 0 ) ) 
                    || fieldType == 'list' ) {
                rows[rowIndex] = document.createElement('div');
                rows[rowIndex].className = "row";
                rows[rowIndex].id = "row_" + rowIndex;
                if (cols[0]) {
                    rows[rowIndex].appendChild(cols[0]);
                    cols[0] = null;
                }
                if (cols[1]) {
                    rows[rowIndex].appendChild(cols[1]);
                    cols[1] = null;
                }
                rowIndex++;
                
            }
            
        }
        // create a header row
        var header = document.createElement('div');
        header.className = "searchSubHeader";
        var sfContainer = document.createElement('div');
        if (searchFields[i].getAttribute('Level') == 1) {
            header.innerHTML = "Packages";
            header.setAttribute('onclick', 'showHideSearchFields(1);');
            header.id = "packageSFHeader";
            sfContainer.id = "SearchFields1";
            sfContainer.style.display = (level == 1) ? "block" : "none";
        } else if (searchFields[i].getAttribute('Level') == 2) {
            header.innerHTML = "Events";
            header.setAttribute('onclick', 'showHideSearchFields(2);');
            header.id = "eventSFHeader";
            sfContainer.id = "SearchFields2";
            sfContainer.style.display = (level == 2) ? "block" : "none";
        } else if (searchFields[i].getAttribute('Level') == 3) {
            header.innerHTML = "Combos";
            header.setAttribute('onclick', 'showHideSearchFields(3);');
            header.id = "comboSFHeader";
            sfContainer.id = "SearchFields3";
            sfContainer.style.display = (level == 3) ? "block" : "none";
        } else if (searchFields[i].getAttribute('Level') == 4) {
            header.innerHTML = "Assets";
            header.setAttribute('onclick', 'showHideSearchFields(4);');
            header.id = "assetSFHeader";
            sfContainer.id = "SearchFields4";
            sfContainer.style.display = (level == 4) ? "block" : "none";
            if ( (level == 3) && (activeEditorPageId == 'eventEditor') ) {
                sfContainer.style.display = "block";
            }
        }
        container.appendChild(header);
        
        for (var j=0; j<rowIndex; j++) {
            sfContainer.appendChild(rows[j]);
        }
        container.appendChild(sfContainer);
        var footer = document.createElement('div');
        footer.className = "row";
        footer.style.height = "5px";
        container.appendChild(footer);        
    }
    
    var row = document.createElement('div');
    row.className = "row";
    var checkEl = document.createElement('input');
    checkEl.type = "checkbox";
    row.appendChild(checkEl);
    var span = document.createElement('span');
    span.style.marginTop = "-2px";
    if (level == 0) {
        checkEl.id = "showDisabledPackagesCheckbox";
        span.innerHTML = "Show disabled packages";
        $('packageSearchButtons').style.display = "block";
    } else if (level == 1) {
        checkEl.id = "showDisabledPackagesCheckbox";
        span.innerHTML = "Show disabled packages";
        $('packageSearchButtons').style.display = "block";
    } else if (level == 2) {
        checkEl.id = "showDisabledEventsCheckbox";
        span.innerHTML = "Show disabled events";
        $('eventSearchButtons').style.display = "block";
    } else if (level == 3) {
        checkEl.id = "showDisabledCombosCheckbox";
        if (activeEditorPageId == "eventEditor") {
            span.innerHTML = "Show disabled combos/assets";
        } else {
            span.innerHTML = "Show disabled combos";
        }
        $('comboSearchButtons').style.display = "block";
    } else if (level == 4) {
        checkEl.id = "showDisabledAssetsCheckbox";
        span.innerHTML = "Show disabled assets";
        $('assetSearchButtons').style.display = "block";
    }
    row.appendChild(span);
    container.appendChild(row);
    
    // special case for combo page
    if (level == 4) {
        comboEditorSFLoaded = true;
        updateComboSFOptions();    
    }
}

// function to insert search values into search xml
function addSearchValuesToXML () {
    var objLevel = 0;
    var sfContainerStr = "";
    if (activeEditorPageId == "scheduleEditor" || activeEditorPageId == "packageList") {
        objLevel = 1;
        sfXML = scheduleSFXML;
        sfContainerStr = activeEditorPageId + "_SearchFields";
    } else if (activeEditorPageId == "packageEditor" || activeEditorPageId == "eventList") {
        objLevel = 2;
        sfXML = packageSFXML;
        sfContainerStr = activeEditorPageId + "_SearchFields";
    } else if (activeEditorPageId == "eventEditor" || activeEditorPageId == "comboList") {
        objLevel = 3;
        sfXML = eventSFXML;
        sfContainerStr = activeEditorPageId + "_SearchFields";
    } else if (activeEditorPageId == "comboEditor" || activeEditorPageId == "assetList") {
        objLevel = 4;
        sfXML = comboSFXML;
        sfContainerStr = activeEditorPageId + "_SearchFields";
    } else if (activeEditorPageId == "liveControl") {
        objLevel = (searchChoice == "Package") ? 1 : 2;
        sfXML = (searchChoice == "Package") ? scheduleSFXML : packageSFXML;
        sfContainerStr = (searchChoice == "Package") ? "liveControl_PackageSearchFields" : "liveControl_EventSearchFields";
    }  else if (activeEditorPageId == "multiPackage") {
        objLevel = 2;
        sfXML = packageSFXML;
        sfContainerStr = activeEditorPageId + "_SearchFields";
    } else if (activeEditorPageId.match('report')) {
        objLevel = 4;
        sfXML = comboSFXML;
        sfContainerStr = "assetSearchFields";
    }
    var sfContainer = $(sfContainerStr);

    var searchFields = sfXML.getElementsByTagName('SearchFields');
    // loop through levels
    for (var i=0, len=searchFields.length; i<len; i++) {
        // get field nodes
        var fieldNodes = [];
        var searchFieldChildren = searchFields[i].childNodes;
        for (j=0, jlen=searchFieldChildren.length; j<jlen; j++) {
            if (searchFieldChildren[j].tagName == "Field") {
                fieldNodes.push(searchFieldChildren[j]);
            }
        }
        // update "Value" attribute
        var level = searchFields[i].getAttribute('Level');
        for (j=0, jlen=fieldNodes.length; j<jlen; j++) {
            var name = fieldNodes[j].getAttribute('Name');
            var inputId = "Level_" + level + "_Name_" + name;
            //var inputEl = $(inputId);
            var selectorStr = "[id='" + inputId + "']";
            var inputEl = sfContainer.getElementsBySelector(selectorStr)[0];
            fieldNodes[j].removeAttribute('Value');
            var fieldType = fieldNodes[j].getAttribute('DataType');
            if (fieldType != 'list') {
                if (fieldType == 'time') {
                    var timeValue = inputEl.value.strip();
                    if ( (timeValue.length > 0) && (timeValue.match(durationRegex)) ) {
                        var durationXML = "1900-01-01T" + padDurationStr(timeValue);
                        fieldNodes[j].setAttribute('Value', durationXML);
                    } else if ( (timeValue.length > 0) && (timeValue.match(timeRegex)) ) { 
                        var timeXML = "1/1/1900 " + timeValue;
                        fieldNodes[j].setAttribute('Value', timeXML);
                    } else {
                        fieldNodes[j].setAttribute('Value', '');  // duration is bad, so set value to nothing 
                    }
                } else {
                    fieldNodes[j].setAttribute('Value', inputEl.value.strip());
                }
            } else {
                if (inputEl.selectedIndex > 0) {
                    fieldNodes[j].setAttribute('Value', inputEl.options[inputEl.selectedIndex].value);
                } else {
                    fieldNodes[j].setAttribute('Value', '');
                }
            }
        }
    } 
    
    // update "include disabled" checkbox
    var sProcNode = sfXML.getElementsByTagName('STOREDPROCEDURE')[0];
    if (objLevel == 1) {
        if ($('showDisabledPackagesCheckbox').checked) {
            sProcNode.removeAttribute('IncludeDisabled');
            sProcNode.setAttribute('IncludeDisabled', 'true');
        } else {
            sProcNode.removeAttribute('IncludeDisabled');
            sProcNode.setAttribute('IncludeDisabled', 'false');
        }
    } else if (objLevel == 2) {
        if ($('showDisabledEventsCheckbox').checked) {
            sProcNode.removeAttribute('IncludeDisabled');
            sProcNode.setAttribute('IncludeDisabled', 'true');
        } else {
            sProcNode.removeAttribute('IncludeDisabled');
            sProcNode.setAttribute('IncludeDisabled', 'false');
        }
    } else if (objLevel == 3) {       
        // also add and update @IncludeAssets for combo/asset search
        var comboFields = sfXML.getElementsByTagName('SearchFields')[0].getElementsByTagName('Field');
        var hasComboValue = false;
        for (var i=0, len=comboFields.length; i<len; i++) {
            var fieldValue = comboFields[i].getAttribute('Value');
            if (fieldValue && fieldValue.length > 0) {
                hasComboValue = true;
                break;
            }
        }
        var assetFields = sfXML.getElementsByTagName('SearchFields')[1].getElementsByTagName('Field');
        var hasAssetValue = false;
        for (var i=0, len=assetFields.length; i<len; i++) {
            var fieldValue = assetFields[i].getAttribute('Value');
            if (fieldValue && fieldValue.length > 0) {
                hasAssetValue = true;
                break;
            }
        }
        if ( (hasComboValue == false) && (hasAssetValue == false) ) { // no search values, return assets
            sProcNode.setAttribute('IncludeAssets', 'true');
        } else if (hasAssetValue == true) {
            sProcNode.setAttribute('IncludeAssets', 'true');
        } else {
            sProcNode.setAttribute('IncludeAssets', 'false');
        }

        if ($('showDisabledCombosCheckbox').checked) {
            sProcNode.removeAttribute('IncludeDisabled');
            sProcNode.setAttribute('IncludeDisabled', 'true');           
        } else {
            sProcNode.removeAttribute('IncludeDisabled');
            sProcNode.setAttribute('IncludeDisabled', 'false');
        }
    } else if (objLevel == 4) {
        if ($('showDisabledAssetsCheckbox').checked) {
            sProcNode.removeAttribute('IncludeDisabled');
            sProcNode.setAttribute('IncludeDisabled', 'true');
        } else {
            sProcNode.removeAttribute('IncludeDisabled');
            sProcNode.setAttribute('IncludeDisabled', 'false');
        }
    }
    
    // call function to scrub values of illegal characters
    scrubSearchValues();
}

// function to reset search fields
function resetSearchFields(containerId) {
    // reset search field xml
    if (activeEditorPageId == "scheduleEditor" || activeEditorPageId == "packageList") {
        sfXML = scheduleSFXML;
    } else if (activeEditorPageId == "packageEditor" || activeEditorPageId == "eventList") {
        sfXML = packageSFXML;
    } else if (activeEditorPageId == "eventEditor" || activeEditorPageId == "comboList") {
        sfXML = eventSFXML;
    } else if (activeEditorPageId == "comboEditor" || activeEditorPageId == "assetList") {
        sfXML = comboSFXML;
    } else if (activeEditorPageId == "liveControl") {
        sfXML = (searchChoice == "Package") ? scheduleSFXML : packageSFXML;
    } else if (activeEditorPageId.match('report')) {
        sfXML = comboSFXML;
    }    
    
    var xmlFields = sfXML.getElementsByTagName('Field');
    for (var i=0, len=xmlFields.length; i<len; i++) {
        xmlFields[i].removeAttribute('Value');
        xmlFields[i].setAttribute('Value', '');
    }
    
    // reset search fields on form
    var container = $(containerId);
    var inputs = container.getElementsByTagName('input');
    for (var i=0, len=inputs.length; i<len; i++) {
        if (inputs[i].getAttribute('disabled') != null) continue;
        if (inputs[i].type == 'text') inputs[i].value = '';
        if (inputs[i].type == 'checkbox') inputs[i].checked = false;
    }
    
    var selects = container.getElementsByTagName('select');
    for (var i=0, len=selects.length; i<len; i++) {
        if (selects[i].getAttribute('disabled') != null) continue;
        if ( (selects[i].getAttribute('onchange') != null) && ((i+1) != len) ) {  // repopulate lists with submeta filters
            selects[i].selectedIndex = 0;
            var level = selects[i].id.split('_')[1];
            var searchFields = sfXML.getElementsByTagName('SearchFields');
            var sfLevelNode = null;
//            // loop through levels
//            for (var j=0, jlen=searchFields.length; j<jlen; j++) {
//                if (searchFields[j].getAttribute('Level') == level) {
//                    sfLevelNode = searchFields[j];
//                    break;
//                }
//            }
//            
//            var fieldNodes = [];
//            var searchFieldChildren = sfLevelNode.childNodes;
//            for (var j=0, jlen=searchFieldChildren.length; j<jlen; j++) {
//                if (searchFieldChildren[j].tagName == "Field") {
//                    fieldNodes.push(searchFieldChildren[j]);
//                }
//            }
            // loop through levels
            var fieldNodes = [];
            for (var j=0, jlen=searchFields.length; j<jlen; j++) {
                var searchFieldChildren = searchFields[j].childNodes;
                for (var k=0, klen=searchFieldChildren.length; k<klen; k++) {
                    if (searchFieldChildren[k].tagName == "Field") {
                        fieldNodes.push(searchFieldChildren[k]);
                    }
                }
            }

            var mdField = null;
            var mdName = selects[i+1].id.split('_')[3];
            updateSFMDOptions(selects[i], level, mdName);
        } else {
            selects[i].selectedIndex = 0;
        }
    }
}

// function to load activity log into editor page
function loadActivityLog(activities, logNode, objStr) {
    var logStr = "";
    for (var i=0, len=activities.length; i<len; i++) {
        var dateArr = parseXMLDate(activities[i].getAttribute('DateTime'));
        var pm = false;
        if (dateArr[3] > 12) {
            dateArr[3] -= 12;
            pm = true;
        } else if (dateArr[3] == 0) {
            dateArr[3] += 12;
        } else if (dateArr[3] == 12) {
            pm = true;
        }
        var dateStr = dateArr[1] + "/" + dateArr[2] + "/" + dateArr[0] + " " +  parseInt(dateArr[3],10).toPaddedString(2,10) + ":" + parseInt(dateArr[4],10).toPaddedString(2,10) + ":" + parseInt(dateArr[5],10).toPaddedString(2,10);
        dateStr += (pm) ? " PM" : " AM";
        var description = activities[i].getAttribute('Description');
        var activityId = activities[i].getAttribute('ActivityID');
        var user = activities[i].childNodes[1].getAttribute('UserName');
        if (activityId == '1000') {
            logStr += dateStr + ": " + objStr + " created by " + user;
            logStr += (description != '') ? (" (" + description + ").<br />") : (".<br />");
        } else if (activityId == '1001') {
            logStr += dateStr + ": " + objStr + " updated by " + user;
            logStr += (description != '') ? (" (" + description + ").<br />") : (".<br />");
        } else if (activityId == '1100') {
            logStr += dateStr + ": " + objStr + " enabled by " + user;
            logStr += (description != '') ? (" (" + description + ").<br />") : (".<br />");
        } else if (activityId == '1101') {
            logStr += dateStr + ": " + objStr + " disabled by " + user;
            logStr += (description != '') ? (" (" + description + ").<br />") : (".<br />");
        }
    }
    logNode.innerHTML = logStr;
}

// function to lock duration and channel for combo searches
function updateComboSFOptions() {
    if (!comboEditorSFLoaded) return;
    if (!comboEditorLoaded) return;
    // load duration and disable
    var sfContainer = $('comboEditor_SearchFields');
    var durationStart = sfContainer.getElementsBySelector('[id="Level_4_Name_Duration.Start"]')[0];
    var durationEnd = sfContainer.getElementsBySelector('[id="Level_4_Name_Duration.End"]')[0];
    var channel = sfContainer.getElementsBySelector('[id="Level_4_Name_Channel"]')[0];
//    sfContainer.getElementById('Level_4_Name_Duration.Start').value = $('comboEditor_Duration').value.strip();
//    sfContainer.getElementById('Level_4_Name_Duration.Start').setAttribute('disabled', 'disabled');
//    sfContainer.getElementById('Level_4_Name_Duration.End').value = $('comboEditor_Duration').value.strip();
//    sfContainer.getElementById('Level_4_Name_Duration.End').setAttribute('disabled', 'disabled');
    durationStart.value = $('comboEditor_Duration').value.strip();
    durationStart.setAttribute('disabled', 'disabled');
    durationEnd.value = $('comboEditor_Duration').value.strip();
    durationEnd.setAttribute('disabled', 'disabled');
    
    // load channel and disable
    var channelValue = $('comboEditor_Channel').options[$('comboEditor_Channel').selectedIndex].value;
    var sfChannelOptions = channel.immediateDescendants();
    for (var i=0, len=sfChannelOptions.length; i<len; i++) {
        if (sfChannelOptions[i].value == channelValue) {
            sfChannelOptions[i].selected = true;
        } else {
            sfChannelOptions[i].selected = false;
        }
    }
    channel.setAttribute('disabled', 'disabled');
    channel.className = "disabledSelect";
    
    // also clear any search results
    clearSearchResults();
}

// function to hide blocks of search fields
function showHideSearchFields(level) {
    var sfId = "SearchFields" + level;
    if ( ($(sfId).style.display == 'block') || ($(sfId).style.display == '') ) {
        $(sfId).style.display = 'none';
    } else {
        $(sfId).style.display = 'block';
    }
}

function updateSFMDOptions(thisList, level, mdField) {
    
    var searchFields = sfXML.getElementsByTagName('SearchFields');
    var sfLevelNode = null
    for (var i=0, len=searchFields.length; i<len; i++) {
        if (searchFields[i].getAttribute('Level') == level) {
            sfLevelNode = searchFields[i];
            break;
        }
    }
    
    var fieldNodes = [];
    var searchFieldChildren = sfLevelNode.childNodes;
    for (var i=0, len=searchFieldChildren.length; i<len; i++) {
        if (searchFieldChildren[i].tagName == "Field") {
            fieldNodes.push(searchFieldChildren[i]);
        }
    }

    // get matching field node
    var mdFieldNode = null;
    for (var i=0, len=fieldNodes.length; i<len; i++) {
        if (fieldNodes[i].getAttribute('Name') == mdField) {
            mdFieldNode = fieldNodes[i];
            break;
        }
    }

    // store list options
    var mdOptions = [];
    var mdChildren = mdFieldNode.childNodes;
    for (var i=0, len=mdChildren.length; i<len; i++) {
        if (mdChildren[i].tagName == 'Option') {
            mdOptions.push(mdChildren[i]);
        }
    }
    
    var mdFieldStr = "Level_" + level + "_Name_" + mdField;
    var mdFieldList = $(mdFieldStr);
    
    // find matching options
    var filteredOptions = [];
    for (var i=0, len=mdOptions.length; i<len; i++) {
        if (mdOptions[i].getAttribute('SubMDID') == thisList.options[thisList.selectedIndex].value) {
            filteredOptions.push(mdOptions[i]);
        }
    }
    
    // clear list
    var options = mdFieldList.immediateDescendants();
    for (var i=0, len=options.length; i<len; i++) {
        options[i].remove();
    }
    
    if (thisList.selectedIndex ==0 ) {
        // load list with all options
        // create default option
        var optionEl = document.createElement('option');
        optionEl.value = "-1";
        optionEl.text = "Select...";
        mdFieldList.options.add(optionEl);
        for (var i=0, len=mdOptions.length; i<len; i++) {
            var optionEl = document.createElement('option');
            optionEl.value = mdOptions[i].getAttribute('ID');
            optionEl.text = mdOptions[i].getAttribute('Name');
            mdFieldList.options.add(optionEl);
        }
    } else {
        // load list with filtered options
        for (var i=0, len=filteredOptions.length; i<len; i++) {
            var optionEl = document.createElement('option');
            optionEl.value = filteredOptions[i].getAttribute('ID');
            optionEl.text = filteredOptions[i].getAttribute('Name');
            mdFieldList.options.add(optionEl);
        }    
    }
}

// function to check combo page and see if updating options can occur
function checkComboOptions() {
    
    // check duration
    var msgNode = $('comboEditor_Messages');
    var errMsg = "";
    msgNode.innerHTML = "";
    msgNode.style.display = "none"; 
    var durationStr = $('comboEditor_Duration').value.strip();
    if (durationStr && !(durationStr.match(durationRegex))) {
        errMsg += "&#149; Combo duration is not formatted correctly<br />";
        msgNode.innerHTML = errMsg;
        msgNode.style.display = "block";
        return;
    } else if (durationStr) {
        // pad duration if necessary
        $('comboEditor_Duration').value = padDurationStr(durationStr).substr(3);
    }
    
    // check to see that nothing is assigned - !!! Enhance
    var showAlert = false;
    var defaultAsset = $('comboEditorDefaultAsset');    
    var dataTagRules = $('comboEditor_DataTagRulesContainer').immediateDescendants();
    var tickerEditors = $('comboEditorTextStrings').immediateDescendants()
    
    if (defaultAsset.firstDescendant()) showAlert = true;
    
    if (!showAlert) {
        for (var i=0, len=dataTagRules.length; i<len; i++) {
            var matchValue = dataTagRules[i].getElementsBySelector('input[type="text"]')[0];
            var assetContainer = dataTagRules[i].getElementsByClassName('assetContainer')[0];
            if ( (matchValue.value.strip() != '') || (assetContainer.firstDescendant()) ) {
                showAlert = true;
                break;
            }
        }
    }
    
    if (!showAlert) {
        if ($('comboEditorTemplateSelect').selectedIndex > 0) showAlert = true;
    }
    
    if (!showAlert) {
         for (var i=0, len=tickerEditors.length; i<len; i++) {
            var textArea = tickerEditors[i].getElementsBySelector('textarea')[0];
            if (textArea.value.strip() != '') {
                showAlert = true;
                break;
            }
        }   
    }
    
    if (showAlert) {
        var spanTxt = "Warning";
        var labelTxt = "Changing the duration or display surface will reset asset associations and text templates.  Continue?";
        var onClickYes = "hideYesNoAlert(); updateComboOptions();";
        var onClickNo = "hideYesNoAlert(); reverseComboChanges();";
        showYesNoAlert(spanTxt, labelTxt, onClickYes, onClickNo);
    } else {
        updateComboOptions();
    }
}

// function to check asset duration
function checkAssetDuration () {
    // check duration
    var msgNode = $('assetEditor_Messages');
    var errMsg = "";
    msgNode.innerHTML = "";
    msgNode.style.display = "none"; 
    var durationStr = $('assetEditor_Duration').value.strip();
    if (durationStr && !(durationStr.match(durationRegex))) {
        errMsg += "&#149; Asset duration is not formatted correctly<br />";
        msgNode.innerHTML = errMsg;
        msgNode.style.display = "block";
        return;
    } else if (durationStr) {
        // pad duration if necessary
        $('assetEditor_Duration').value = padDurationStr(durationStr).substr(3);
    }
}

// function to show generic yes no alert
function showYesNoAlert(spanTxt, labelTxt, onClickYes, onClickNo) {
    //prep the fields
    var width = $('yesNoPopup').getWidth();
    $('yesNoHeader').style.width = (width-5) + "px";
    $('yesNoSpan').innerHTML = spanTxt;
    $('yesNoLabel').innerHTML = labelTxt;
    $('yesNo_YesBtn').setAttribute('onclick', onClickYes);
    $('yesNo_NoBtn').setAttribute('onclick', onClickNo);
    $('yesNoPopup').style.display = "block";
    coverPageForAlert($('yesNoPopup'));
}

function hideYesNoAlert() {
    uncoverPageForAlert();
    $('yesNoPopup').style.display = "none";
}

// function to show generic alert with ok button
function showAlertPopup(spanTxt, labelTxt, onClickOK) {
    //prep the fields
    var width = $('alertPopup').getWidth();
    $('alertHeader').style.width = (width-5) + "px";
    $('alertSpan').innerHTML = spanTxt;
    $('alertLabel').innerHTML = labelTxt;
    $('alertBtn').setAttribute('onclick', onClickOK);
    $('alertPopup').style.display = "block";
}

function hideAlertPopup() {
    var docEls = $('pageContainer').descendants();
    var matchingId = "";
    var alertShadowMatch = /Alert_DropShadow/;
    for (var i=0, len=docEls.length; i<len; i++) {
        if (docEls[i].id.search(alertShadowMatch) >= 0) {
            matchingId = docEls[i].id;
            break;
        }
    }
    var shadowEl = $(matchingId);
    //var shadowEl = $('ctl00_ContentPlaceHolder_Main_Panel_Alert_DropShadow');
    shadowEl.style.width = "0px";
    // reset popup values
    $('alertPopup').style.width = "";
    $('alertHeader').style.backgroundColor = "#507BAF";
    $('alertSpan').innerHTML = "";
    $('alertLabel').innerHTML = "";
    $('alertBtn').setAttribute('onclick', 'hideAlertPopup();');
    $('alertPopup').style.display = "none";
}

function reverseComboChanges() {
    $('comboEditor_Duration').value = prevComboDuration;
    $('comboEditor_Channel').selectedIndex = prevComboChannelIndex;
}

// function to update video sources based on change in channel
function updateVideoSources() {
    // update videosource dropdown
    var sourceSelect = (activeEditorPageId == 'comboEditor') ? $('comboEditor_VideoSource') : $('assetEditor_VideoSource');
    var sourceOptions = sourceSelect.immediateDescendants();
    // remove current options
    for (var i=1, len=sourceOptions.length; i<len; i++) {
        sourceOptions[i].remove();
    }
    // add options associated with channel
    var channelSelect = (activeEditorPageId == 'comboEditor') ? $('comboEditor_Channel') : $('assetEditor_Channel');
    var selectedChannel = channelSelect.options[channelSelect.selectedIndex].value; 
    var sources = null;
    if (activeEditorPageId == 'comboEditor') {
        sources = comboRequest.responseXML.getElementsByTagName('VIDEOSOURCE');
    } else {
        sources = assetRequest.responseXML.getElementsByTagName('VIDEOSOURCE');
    }
    if (selectedChannel == 0) {
        // populate all video sources
        for (var i=0, len=sources.length; i<len; i++) {
            var optionEl = document.createElement('option');
            optionEl.text = sources[i].getAttribute('Name');
            optionEl.value = sources[i].getAttribute('CueString');
            sourceSelect.options.add(optionEl);
        } 
        // disable list until a channel is chosen again
        sourceSelect.setAttribute('disabled', 'disabled');
    } else {	
        // populate video sources matching selected channel	
        for (var i=0, len=sources.length; i<len; i++) {
            if (selectedChannel == sources[i].getAttribute('ChannelID')) {
                var optionEl = document.createElement('option');
                optionEl.text = sources[i].getAttribute('Name');
                optionEl.value = sources[i].getAttribute('CueString');
                sourceSelect.options.add(optionEl);
            }
        }  
        // enable list
        sourceSelect.removeAttribute('disabled');
    }
}

// make updates to editor page after updating duration and display surface
function updateComboOptions() {  
    
    if ( ($('comboEditor_Duration').value.strip() != '') && ($('comboEditor_Channel').selectedIndex != 0) ) {
        updateComboSFOptions();
    
        $('comboEditor_NoAssets').style.display = "none";
        $('comboEditor_Assets').style.display = "block";
        $('comboEditor_NoTemplates').style.display = "none";
        $('comboEditor_Templates').style.display = "block";
        
        // assign new values to globals
        prevComboDuration = $('comboEditor_Duration').value.strip();
        prevComboChannelIndex = $('comboEditor_Channel').selectedIndex;
        
        // remove asset and tag associations
        // remove item from drag container if exists
        var dragContainer = $('comboEditorAssetIcon');   
	    if (dragContainer.firstDescendant()) dragContainer.firstDescendant().remove();
	    // remove default asset if exists
	    var defaultAsset = $('comboEditorDefaultAsset');
	    if (defaultAsset.firstDescendant()) defaultAsset.firstDescendant().remove();
	    // remove data rules
        var dataTagRules = $('comboEditor_DataTagRulesContainer').immediateDescendants();
        for (var i=0, len=dataTagRules.length; i<len; i++) {
            dataTagRules[i].remove();
        }
        
        // remove template options
        var templateSelectOptions = $('comboEditorTemplateSelect').immediateDescendants();
        for (var i=1, len=templateSelectOptions.length; i<len; i++) {
            templateSelectOptions[i].remove();
        }
        
        // remove text string boxes - !!! Enhance
        var tickerEditors = $('comboEditorTextStrings').immediateDescendants();
        for (var i=0, len=tickerEditors.length; i<len; i++) {
            tickerEditors[i].remove();
        }
        
        // populate asset and tag associations
        loadAssetsForCombo();
        // load templates
        loadTextTemplates();	     
    }
}

// function to load assets associated with this combo
function loadAssetsForCombo () {
    comboSpots = comboRequest.responseXML.getElementsByTagName('COMBOVIDLISTSPOT');
    if (comboSpots.length == 1) {
        // create and render default asset
        var defaultContainer = $('comboEditorDefaultAsset');
        var assetXML = comboSpots[0].childNodes[1];
        var assetPeca = loadAssetFromXML(assetXML);
        var assetPecaEl = assetPeca.render();
        var dimensions = defaultContainer.getDimensions();
        assetPecaEl.style.width = (dimensions.width-2) + "px";
        assetPecaEl.style.height = (dimensions.height-2) + "px";
        defaultContainer.appendChild(assetPecaEl);
        addDrag(assetPecaEl);    
        // add one row
        appendNewDataTagRule(null)
    } else if (comboSpots.length > 1) {
        spotOrder = [];
        // render rules and get order returned by xml
        for (var i=0, len=comboSpots.length-1; i<len; i++ ) {
            spotOrder.push(comboSpots[i].getAttribute('Index'));
            appendNewDataTagRule(null);
        }
        spotOrder.push(comboSpots[comboSpots.length-1].getAttribute('Index'))
        // load the appropriate values
        for (var i=0, len=comboSpots.length-1; i<len; i++ ) {
            // get elements from rule row
            var ruleStr = "comboEditor_DataTagRule_" + i;
            var rule = $(ruleStr);
            var selects = rule.getElementsByTagName('select');
            var dataTagSelect = selects[0];
            var comparatorSelect = selects[1];
            var matchValueInput = rule.getElementsBySelector('input[type="text"]')[0];
            var assetContainer = rule.getElementsByClassName('assetContainer')[0];
            // get index for combo spot
            var index = (i+1).toString(); 
            index = spotOrder.indexOf(index);
            // assign values
            for (var j=0, jlen=dataTagSelect.options.length; j<jlen; j++) {
                if (dataTagSelect.options[j].value == comboSpots[index].getAttribute('DataTagID')) {
                    dataTagSelect.options[j].selected = true;
                } else {
                    dataTagSelect.options[j].selected = false;
                }
            }
            for (var j=0, jlen=comparatorSelect.options.length; j<jlen; j++) {
                if (comparatorSelect.options[j].value == comboSpots[index].getAttribute('Comparator')) {
                    comparatorSelect.options[j].selected = true;
                } else {
                    comparatorSelect.options[j].selected = false;
                }
            }
            // add class to match input - being called too early
            updateDataTagValueType(dataTagSelect);
            
            matchValueInput.value = comboSpots[index].getAttribute('MatchValue');
            
            // create asset and attach to asset container
            var assetXML = comboSpots[index].childNodes[1];
            var assetPeca = loadAssetFromXML(assetXML);
            var assetPecaEl = assetPeca.render();
            var dimensions = assetContainer.getDimensions();
            assetPecaEl.style.width = (dimensions.width-2) + "px";
            assetPecaEl.style.height = (dimensions.height-2) + "px";
            assetContainer.appendChild(assetPecaEl);
            addDrag(assetPecaEl);
        }
        
        // create and render default asset
        var index = (comboSpots.length).toString(); 
        index = spotOrder.indexOf(index);
        var defaultContainer = $('comboEditorDefaultAsset');
        var assetXML = comboSpots[index].childNodes[1];
        var assetPeca = loadAssetFromXML(assetXML);
        var assetPecaEl = assetPeca.render();
        var dimensions = defaultContainer.getDimensions();
        assetPecaEl.style.width = (dimensions.width-2) + "px";
        assetPecaEl.style.height = (dimensions.height-2) + "px";
        defaultContainer.appendChild(assetPecaEl);
        addDrag(assetPecaEl);
    } else if ($('comboEditor_DataTagRulesContainer').immediateDescendants().length < 1) {
        appendNewDataTagRule(null)
    }
}

// function to append a new blank data tag rule
function appendNewDataTagRule (btn) {
    var index = dataTagRuleIndex++;
    
    var container = $('comboEditor_DataTagRulesContainer');
    
    // create row
    var row = document.createElement('div');
    row.id = "comboEditor_DataTagRule_" + index;
    row.style.width = "880px;";
    row.style.height = "50px;";
    
    // create first column and its elements
    var col1 = document.createElement('div');
    col1.className = "col";
    //col1.style.marginTop = "9px";
    var btnAdd = document.createElement('input');
    btnAdd.setAttribute('type', 'button');
    btnAdd.setAttribute('value', '+');
    btnAdd.setAttribute('onclick', 'appendNewDataTagRule(this);');
    var spacerS = document.createElement('div');
    spacerS.className = "spacerS";
    var btnMinus = document.createElement('input');
    btnMinus.setAttribute('type', 'button');
    btnMinus.setAttribute('value', '-');
    Event.observe(btnMinus, 'click', removeDataTagRule);
    var spacerL1 = document.createElement('div');
    spacerL1.className = "spacerL";
    var dataTagSelect = document.createElement('select');
    //dataTagSelect.className = "widthS";
    var dataTags = comboRequest.responseXML.getElementsByTagName('DATATAG');
    for (var i=0, len=dataTags.length; i<len; i++) {
        var optionEl = document.createElement('option');
        optionEl.value = dataTags[i].getAttribute('ID');
        optionEl.text = dataTags[i].getAttribute('Name');
        dataTagSelect.options.add(optionEl);
    }   
    dataTagSelect.setAttribute('onchange', 'updateDataTagValueType(this);'); 
    var spacerL2 = document.createElement('div');
    spacerL2.className = "spacerL";
    var comparator = document.createElement('select');
    //comparator.className = "widthM";
    var option1 = document.createElement('option');
    option1.value = "=";
    option1.text = "=";
    var option2 = document.createElement('option');
    option2.value = "!=";
    option2.text = "!=";   
    var option3 = document.createElement('option');
    option3.value = ">";
    option3.text = ">";
    var option4 = document.createElement('option');
    option4.value = ">=";
    option4.text = ">=";                
    var option5 = document.createElement('option');
    option5.value = "<";
    option5.text = "<";   
    var option6 = document.createElement('option');
    option6.value = "<=";
    option6.text = "<=";
    // add options to select
    comparator.options.add(option1);
    comparator.options.add(option2);
    comparator.options.add(option3);
    comparator.options.add(option4);
    comparator.options.add(option5);
    comparator.options.add(option6);
    var spacerL3 = document.createElement('div');
    spacerL3.className = "spacerL";
    var matchValue = document.createElement('input');
    matchValue.setAttribute('type', 'text');
    matchValue.className = "widthS";
    matchValue.setAttribute('onchange', 'validateDataTagValue(this); setPageModified(true);');
    var spacerL4 = document.createElement('div');
    spacerL4.className = "spacerL";
    var arrow = document.createElement('img');
    arrow.setAttribute('src','images/arrow_right.gif');
    arrow.style.float = "left";
    var spacerL5 = document.createElement('div');
    spacerL5.className = "spacerL";
    
    // append elements to first column
    col1.appendChild(btnAdd);
    col1.appendChild(spacerS);
    col1.appendChild(btnMinus);
    col1.appendChild(spacerL1);
    col1.appendChild(dataTagSelect);
    col1.appendChild(spacerL2);
    col1.appendChild(comparator);
    col1.appendChild(spacerL3);
    col1.appendChild(matchValue);
    col1.appendChild(spacerL4);
    col1.appendChild(arrow);
    col1.appendChild(spacerL5);
    
    // create second column and its elements
    var col2 = document.createElement('div');
    col2.className = "col";
    var spacerL6 = document.createElement('div');
    spacerL6.className = "spacerL";
    var asset = document.createElement('div');
    asset.className = "assetContainer";
    asset.id = "assetDrop_" + index;
    
    // append element to second column
    col2.appendChild(spacerL6);
    col2.appendChild(asset);
    
    // append columns to row
    row.appendChild(col1);
    row.appendChild(col2);
    
    // append row to container
    if ( (container.immediateDescendants().length == 0) || (btn == null) ) {
        // add to end
        container.appendChild(row);
    } else {
        // add after the current row
        var callingRow = btn.parentNode.parentNode;
        if (callingRow.nextSiblings().length == 0) {
            // again, append to end
            container.appendChild(row);
        } else {
            var next = callingRow.next();
            container.insertBefore(row, next);
        }
    }
    
    // check to see if we should disable the minus btn
    if (container.immediateDescendants().length == 1) {
        var minusBtn = container.getElementsBySelector('input[type="button"]')[1];
	    minusBtn.setAttribute('disabled', 'disabled');
    } else {
        var minusBtn = container.getElementsBySelector('input[type="button"]')[1];
	    minusBtn.removeAttribute('disabled');
    }
    
    // add drop to new asset container
    addDrop(asset);
}

// function to add value type to data tag input field
function updateDataTagValueType(tagSelect) {
    var dataTagText = tagSelect.options[tagSelect.selectedIndex].text;
    var matchValueInput = tagSelect.next(3);
    matchValueInput.value = "";
    if (dataTagText == '[DataTag_Date]') {  // add class to input and drop down calendars
        matchValueInput.addClassName('dataTagDate');
        matchValueInput.setAttribute('onfocus', 'this.select();lcs(this);');
        matchValueInput.setAttribute('onclick', 'event.cancelBubble=true;this.select();lcs(this);');
    } else if (dataTagText == '[DataTag_DayOfWeek]') {  // add class to input
        matchValueInput.addClassName('dataTagDayOfWeek');
    } else if (dataTagText == '[DataTag_NightOfWeek]') {  // add class to input
        matchValueInput.addClassName('dataTagNightOfWeek');
    } else if (dataTagText == '[DataTag_Time]') {  // add class to input
        matchValueInput.addClassName('dataTagTime');
    } else if (dataTagText == '[DataTag_DateTime]') {  // add class to input
        matchValueInput.addClassName('dataTagDateTime');
    }
}

var dataTagDayRegex = /^((Monday)|(Tuesday)|(Wednesday)|(Thursday)|(Friday)|(Saturday)|(Sunday))?$/;
var dataTagDateRegex = /^(\d{4}-[0-1]?\d-[0-3]?\d)?$/;
var dataTagTime = /^([0-2]\d:[0-5]\d:[0-5]\d)?$/;
var dataTagDateTime = /^(\d{4}-[0-1]?\d-[0-3]?\d [0-2]\d:[0-5]\d:[0-5]\d)?$/;
// function to validate a data tag value
function validateDataTagValue (matchValueInput) {
    var matchValue = matchValueInput.value;
    var dataTagSelect = matchValueInput.previous(3);
    var dataTagText = dataTagSelect.options[dataTagSelect.selectedIndex].text;
    var errMsg = "";
    var alertNode = $('dataTagAlerts');
    alertNode.style.display = "none";
    if (dataTagText == '[DataTag_Date]') { 
        if (!(matchValue.match(dataTagDateRegex))) {
            errMsg += "[DataTag_Date] value is not formatted correctly.  Please format as \"yyyy-mm-dd\".";
            alertNode.innerHTML = errMsg;
            alertNode.style.display = "block";
        }
    } else if (dataTagText == '[DataTag_DayOfWeek]') { 
        if (!(matchValue.match(dataTagDayRegex))) {
            errMsg += "[DataTag_DayOfWeek] value is not formatted correctly.  Please format as \"Monday\", \"Tuesday\", etc.";
            alertNode.innerHTML = errMsg;
            alertNode.style.display = "block";
        }
    } else if (dataTagText == '[DataTag_NightOfWeek]') { 
        if (!(matchValue.match(dataTagDayRegex))) {
            errMsg += "[DataTag_NightOfWeek] value is not formatted correctly.  Please format as \"Monday\", \"Tuesday\", etc.";
            alertNode.innerHTML = errMsg;
            alertNode.style.display = "block";
        }
    } else if (dataTagText == '[DataTag_Time]') {  
        if (!(matchValue.match(dataTagTime))) {
            errMsg += "[DataTag_Time] value is not formatted correctly.  Please format as \"hh:mm:ss\".";
            alertNode.innerHTML = errMsg;
            alertNode.style.display = "block";
        }
    } else if (dataTagText == '[DataTag_DateTime]') { 
        if (!(matchValue.match(dataTagDateTime))) {
            errMsg += "[DataTag_DateTime] value is not formatted correctly.  Please format as \"yyyy-mm-dd hh:mm:ss\".";
            alertNode.innerHTML = errMsg;
            alertNode.style.display = "block";
        }
    }
}

// function to add list item to icon
function addAssetToCombo () {
    var listBox = $('comboEditorResults');
    if (listBox.selectedIndex < 0) return;
    
    //var assetIcon = $('comboEditorAssetIcon');
    var assetIcon = activeEditor.dragContainer;
    if (assetIcon.firstDescendant()) assetIcon.firstDescendant().remove();
    
    var asset = activeEditor.getPecaById(listBox.options[listBox.selectedIndex].value);
    
    var dragPeca = asset.copy();
    var dragPecaEl = dragPeca.render();
    var dimensions = assetIcon.getDimensions();
    dragPecaEl.style.width = (dimensions.width - 2) + "px";
    dragPecaEl.style.height = (dimensions.height - 2) + "px";
    
    activeEditor.dragContainer.appendChild(dragPecaEl);
    addDrag(dragPecaEl);
    activeEditor.draggablePecas.push(dragPeca);
}

// function to remove an asset from a slot in the combo editor
function removeAssetFromCombo () {
    if (!activeEditor.selectedCell) return;
    activeEditor.selectedCell.remove();
    activeEditor.selectedCell = null;
}

// function to remove a data tag rule
function removeDataTagRule(e) {
    var container = $('comboEditor_DataTagRulesContainer');
    var dataTagRows = container.immediateDescendants();
    if (dataTagRows.length == 1) return;

    var eventEl = Event.element(e);
    Event.stopObserving(eventEl, 'click', removeDataTagRule);
    var rowId = eventEl.parentNode.parentNode;
    var dataTagRow = $(rowId);
    
    dataTagRow.remove();
    var updatedRows = container.immediateDescendants();
    if (updatedRows.length == 1) {
        var minusBtn = container.getElementsBySelector('input[type="button"]')[1];
	    minusBtn.setAttribute('disabled', 'disabled');
    }
}

var tickerEditorRequest = new XMLHttpRequest();
var tickerEditorResponseXML = null;
// function to populate ticker editor XML
function populateTickerEditorXML () {
    // if necessary make request for ticker editor variables to pass to editors - only needs to be done once per page
    if (tickerEditorRequest.responseXML == null) {  // get response if not completed yet
        var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetTickerTags\" />";
        var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
        xmlStr += "<ROOT>";
        xmlStr += sProc;
        xmlStr += "</ROOT>";
        url = "AjaxPost.aspx";
        tickerEditorRequest.open('POST', url, false);
        tickerEditorRequest.setRequestHeader("Content-Type", "text/xml");
        tickerEditorRequest.send(xmlStr);
        // handle response
        if (tickerEditorRequest.readyState == 4) {
            if (tickerEditorRequest.status == 200) {
                if (tickerEditorRequest.responseXML != null) { // set global value to maintain this result
                    tickerEditorResponseXML = tickerEditorRequest.responseXML;
                }
            }
        }
    }
}


// function to load text templates
function loadTextTemplates () {
    var textTemplates = comboRequest.responseXML.getElementsByTagName('TEXTTEMPLATE');
    var templateSelect = $('comboEditorTemplateSelect');
    
    // if list is populated, then remove options first
    var options = templateSelect.immediateDescendants();
    if (options.length > 1) {
        for (var i=1, len=options.length; i<len; i++) {
            options[i].remove();
        }
    }
    
    var comboDurationStr = $('comboEditor_Duration').value.strip();
    var comboChannel = $('comboEditor_Channel').options[$('comboEditor_Channel').selectedIndex].value;
    
    // new adds all templates and edit loads those matching duration and channel
    for (var i=0, len=textTemplates.length; i <len; i++) {
        var templateDuration = parseXMLDate(textTemplates[i].getAttribute('Duration'));
        var templateDurationStr = templateDuration[3] + ":" + templateDuration[4] + ":" + templateDuration[5];
        var templateChannel = textTemplates[i].getAttribute('Channels').split(',')[1];
        if ( (compareDurations(comboDurationStr, templateDurationStr)) && (comboChannel == templateChannel) ) {
            var optionEl = document.createElement('option');
            optionEl.value = textTemplates[i].getAttribute('ID');
            optionEl.text = textTemplates[i].getAttribute('Name');
            templateSelect.options.add(optionEl);
        }
    }
    
    // load selected template for edit screen
    var combo = comboRequest.responseXML.getElementsByTagName('ASSET');
    var ttId = combo[0].getAttribute('TextTemplateID');
    if (ttId) {
        for (var i=0, len=templateSelect.options.length; i<len; i++) {
            if (templateSelect.options[i].value == ttId) {
                templateSelect.options[i].selected = true;
            } else {
                templateSelect.options[i].selected = false;
            }
        }
    }
    
    // if necessary make request for ticker editor variables to pass to editors - only needs to be done once per page
    if (tickerEditorRequest.responseXML == null) {  // get response if not completed yet
        var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetTickerTags\" />";
        var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
        xmlStr += "<ROOT>";
        xmlStr += sProc;
        xmlStr += "</ROOT>";
        url = "AjaxPost.aspx";
        tickerEditorRequest.open('POST', url, false);
        tickerEditorRequest.setRequestHeader("Content-Type", "text/xml");
        tickerEditorRequest.send(xmlStr);
        // handle response
        if (tickerEditorRequest.readyState == 4) {
            if (tickerEditorRequest.status == 200) {
                if (tickerEditorRequest.responseXML != null) { // set global value to maintain this result
                    tickerEditorResponseXML = tickerEditorRequest.responseXML;
                }
            }
        }
    }
    populateTickerEditorXML();
    updateTextStringRows();
}

// function to compare durations
function compareDurations(durStr1, durStr2) {
    durStr1 = padDurationStr(durStr1);
    durStr2 = padDurationStr(durStr2);
    if (durStr1 == durStr2) return true;
    return false;
}

// function to pad a duration string
function padDurationStr(durStr) {
    if (durStr.indexOf(':') == -1) { // only seconds
        durStr = "00:00:" + parseInt(durStr,10).toPaddedString(2,10);
    } else if (durStr.split(':').length == 2)  { // seconds and minutes
        durSplit = durStr.split(':');
        durStr = "00:" + parseInt(durSplit[0],10).toPaddedString(2,10) + ":" + parseInt(durSplit[1],10).toPaddedString(2,10);
    } else if (durStr.split(':').length == 3)  { // seconds, minutes, and hours
        durSplit = durStr.split(':');
        durStr = parseInt(durSplit[0],10).toPaddedString(2,10) + ":" + parseInt(durSplit[1],10).toPaddedString(2,10) + ":" + parseInt(durSplit[2],10).toPaddedString(2,10);
    }
    return durStr;
}

// function to update text string rows - !!! Enhance
function updateTextStringRows () {
    var templateSelect = $('comboEditorTemplateSelect');
    // enable preview button if selection is made
    if (templateSelect.selectedIndex > 0) {
        $('comboEditor_TemplatePreviewBtn').removeAttribute('disabled');
    } else {
        $('comboEditor_TemplatePreviewBtn').setAttribute('disabled', 'disabled');
    }
    
    // get text template node
    var textTemplates = comboRequest.responseXML.getElementsByTagName('TEXTTEMPLATE');
    var textTemplateNode = null;
    for (var i=0, len=textTemplates.length; i<len; i++) {
        if (textTemplates[i].getAttribute('ID') == templateSelect.options[templateSelect.selectedIndex].value) {
            textTemplateNode = textTemplates[i];
            break;
        }
    } 
    // display text template's description
    if (textTemplateNode) {
        var templateDescription = textTemplateNode.getAttribute('Description');
        if (templateDescription != '') $('comboEditorTemplateDescTextArea').value = templateDescription;
        $('comboEditorTemplateDescription').style.display = "block";
    } else {
        $('comboEditorTemplateDescription').style.display = "none";
    }
    
    // get count of required text strings based on selected template
    var ttElements = comboRequest.responseXML.getElementsByTagName('TTELEMENT');
    var ttElementCount = 0;
    for (var i=0, len=ttElements.length; i<len; i++) {
        if (ttElements[i].getAttribute('TextTemplateID') == templateSelect.options[templateSelect.selectedIndex].value)
            ttElementCount++;
    }    
    // get count of rows already appended
    //$('comboEditorTextStrings').immediateDescendants().length; - WGO Unnecessary line of code removed 6/1/08
    var textStringRowCount = $('comboEditorTextStrings').immediateDescendants().length;
    
    // adjust number of rows depending on counts
    if (ttElementCount > textStringRowCount) {  // append extra rows
        for (var i=textStringRowCount; i<ttElementCount; i++) {
            appendTextStringRow(i+1);
        }
    } else if (ttElementCount < textStringRowCount) {
        for (var i=textStringRowCount; i>ttElementCount; i--) {
            var lastRow = $('comboEditorTextStrings').immediateDescendants().pop()
            lastRow.remove();
        }
    }    
    
    // hide custom color popup in case it's visible   
    hideCustomFontColorTag();
}

// !!! Enhance
function appendTextStringRow(index) {
    var container = $('comboEditorTextStrings');
    
    // Replacing with new ticker editor code //
    
    var tickerEditor = new  TickerEditor()
    tickerEditor.load(index, 'Text String', '', container, tickerEditorResponseXML, null);
    tickerEditor.render();
    
    
//    // create elements for text string
//    var row = document.createElement('div');
//    row.className = "row";
//    var col1 = document.createElement('div');
//    col1.className = "col widthL";
//    var labelStr = document.createElement('label');
//    var span = document.createElement('span');
//    span.innerHTML = "Text String " + index;
//    var link = document.createElement('a');
//    link.innerHTML = "Preview";
//    link.className = "right";
//    link.style.display = "none";
//    link.id = "textStringPreviewLink_" + index;
//    var text = document.createElement('textarea');
//    text.className = "heightM widthXL";
//    text.id ="textStringText_" + index;
//    link.setAttribute('onclick', 'showTextStringPreview("'+ text.id + '");');
////    link.setAttribute('onclick', 'var text = $('+text.id+').value; showAlertPopup('Text String Preview', text, hideAlertPopup);');
//    
//    // append elements
//    labelStr.appendChild(span);
//    labelStr.appendChild(link);
//    col1.appendChild(labelStr);
//    col1.appendChild(text);
//    row.appendChild(col1);
//    container.appendChild(row);   
    
    // load values if they exist
    var textStrings = comboRequest.responseXML.getElementsByTagName('TEXTSTRING');
    for (var i=0, len=textStrings.length; i<len; i++) {
        if (index == textStrings[i].getAttribute('Index')) {
            tickerEditor.tickerTextArea.value = textStrings[i].getAttribute('String');
            break;
        }
    }
}

// function to show text string preview - !!! Enhance
function validateTextString(textAreaEl) {
    var textString = $(textAreaEl).value;
    textString = escapeForXML(textString);
    // make request to db
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_TestComboTextString\" Text=\"" + textString + "\" />";
    
    // create xml
    var stringPreviewRequest = new XMLHttpRequest();
    var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
    xmlStr += "<ROOT>";
    xmlStr += sProc;
    xmlStr += "</ROOT>";
    url = "AjaxPost.aspx";
    stringPreviewRequest.open('POST', url, false);
    stringPreviewRequest.setRequestHeader("Content-Type", "text/xml");
    stringPreviewRequest.send(xmlStr);
    
    var response = stringPreviewRequest.responseText;
    if (response.indexOf('<span style="color:Red; font-weight:bold">') == -1) {
        return "";
    } else {
        return response;
    }
}

// new function to show text string preview - !!! Enhance
function showTextStringPreview(textAreaEl) {
    //var textString = $(textAreaEl).value.strip(); WGO 11/26/07: Removing strip() per request
    var textString = $(textAreaEl).value;
    
    // escape for xml
    textString = escapeForXML(textString);
    // replace nasty asciis with friendlier ones
    textString = replaceExtendedASCIIChars(textString);
    // escape newlines and tabs
    textString = textString.replace(/\n/g,"");
    textString = textString.replace(/\t/g,"");
    textString = textString.replace(/\r/g,"");  // not sure about this one yet

    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = parseInt(date.getHours(),10).toPaddedString(2,10);
    var minute = parseInt(date.getMinutes(),10).toPaddedString(2,10);
    var second = parseInt(date.getSeconds(),10).toPaddedString(2,10);
    var dateStr = year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":" + second;
    // make request to db
    var sProc = "<STOREDPROCEDURE Name=\"sproc_TEXT_ResolveString\" Date=\"" + dateStr + "\" Text=\"" + textString + "\" />";
    
    // create xml
    var stringPreviewRequest = new XMLHttpRequest();
    var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
    xmlStr += "<ROOT>";
    xmlStr += sProc;
    xmlStr += "</ROOT>";
    url = "AjaxPost.aspx";
    stringPreviewRequest.open('POST', url, false);
    stringPreviewRequest.setRequestHeader("Content-Type", "text/xml");
    stringPreviewRequest.send(xmlStr);
    
    var response = stringPreviewRequest.responseText;
    var onClickOK = "hideAlertPopup();";
    showAlertPopup('Text String Preview', response, onClickOK);   
}

// !!! Enhance
function resolveTextString(textAreaEl) {
    //var textString = $(textAreaEl).value.strip(); WGO 11/26/07: Removing strip() per request
    var textString = $(textAreaEl).value;
    
    // escape for xml
    textString = escapeForXML(textString);
    // replace nasty asciis with friendlier ones
    textString = replaceExtendedASCIIChars(textString);
    // escape newlines and tabs
    textString = textString.replace(/\n/g,"");
    textString = textString.replace(/\t/g,"");
    textString = textString.replace(/\r/g,"");  // not sure about this one yet
    
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = parseInt(date.getHours(),10).toPaddedString(2,10);
    var minute = parseInt(date.getMinutes(),10).toPaddedString(2,10);
    var second = parseInt(date.getSeconds(),10).toPaddedString(2,10);
    var dateStr = year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":" + second;
    // make request to db
    var sProc = "<STOREDPROCEDURE Name=\"sproc_TEXT_ResolveString\" Date=\"" + dateStr + "\" Text=\"" + textString + "\" />";
    
    // create xml
    var stringPreviewRequest = new XMLHttpRequest();
    var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
    xmlStr += "<ROOT>";
    xmlStr += sProc;
    xmlStr += "</ROOT>";
    url = "AjaxPost.aspx";
    stringPreviewRequest.open('POST', url, false);
    stringPreviewRequest.setRequestHeader("Content-Type", "text/xml");
    stringPreviewRequest.send(xmlStr);
    
    var response = stringPreviewRequest.responseText;
    return response;
}

// !!! Enhance
function showTemplatePreview() {
    // get ttelements
    var templateSelect = $('comboEditorTemplateSelect');
    var ttElements = comboRequest.responseXML.getElementsByTagName('TTELEMENT');
    var selectedTTElements = [];
    for (var i=0, len=ttElements.length; i<len; i++) {
        if (ttElements[i].getAttribute('TextTemplateID') == templateSelect.options[templateSelect.selectedIndex].value) {
            selectedTTElements.push(ttElements[i]);
        }
    }
    
    var textStrings = $('comboEditorTextStrings').getElementsByTagName('textarea');
    
    // check text strings for errors  - WGO: Commenting out until stored procedure is fully tested
    var invalidTxt = "";
    for (var i=0, len=textStrings.length; i<len; i++) {
        var response = validateTextString(textStrings[i]);
        if (response != '') {
            invalidTxt += "<div><span style='font-weight:bold;'>Text String ";
            invalidTxt += (i+1) + "</span></div><br /><br /><div>";
            invalidTxt += response + "</div><br /><br />";
        }
    }
    
    if (invalidTxt != '') {
        var onClickOK = "hideAlertPopup();"
        var alertStr = "Warning - Improperly Formed Tags";
        $('alertPopup').style.width = "700px";
        showAlertPopup(alertStr, invalidTxt, onClickOK);  
        window.scrollTo(0,0);  
    }
    
    // get resolved text strings
    var resolvedStrings = [];
    for (var i=0, len=textStrings.length; i<len; i++) {
        resolvedStrings.push(resolveTextString(textStrings[i]));
    }
    
    if (selectedTTElements.length != resolvedStrings.length) alert('Mismatch in number of ttelements and strings');

    var channelSelect = $('comboEditor_Channel');
    var channelId = channelSelect.options[channelSelect.selectedIndex].value;
    var channelName = channelSelect.options[channelSelect.selectedIndex].text;
    
    var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
    xmlStr += "<Channel ChannelID=\"" + channelId + "\" ChannelName=\"" + channelName + "\" StartTime=\"00:00:00/00\" EndTime=\"00:30:00/00\" UpdateID=\"0\">";
    xmlStr += "<Combo ComboID=\"1\" ComboName=\"Test\" TimelineTime=\"00:00:00/00\" RealTime=\"12:00:00/00\" Duration=\"00:30:00/00\" UpdatedTime=\"12:00:00/00\">";
    for (var i=0,len=resolvedStrings.length; i<len; i++) {
        xmlStr += "<TextString TextStringIndex=\"" + (i+1) + "\">";
        xmlStr += "<String><![CDATA[" + resolvedStrings[i] + "]]></String>";
        xmlStr += "<Details>" + selectedTTElements[i].getAttribute('Details') + "</Details>";
        xmlStr += "</TextString>";
    }
    xmlStr += "</Combo></Channel>";
   
    var url = "WriteTemplatePreview.aspx";
    var templatePreviewRequest = new XMLHttpRequest();
    templatePreviewRequest.open('POST', url, false);
    templatePreviewRequest.setRequestHeader("Content-Type", "text/plain");
    templatePreviewRequest.send(xmlStr);
    
    if (templatePreviewRequest.responseText == '1') {
        // open window and start writing       
        var win = window.open('Exports/DownloadTemplatePreview.aspx','DownloadTemplatePreview', 'scrollbars=0, resizable=0, width=10, height=10');
        win.blur();
    }

}

function getTaskOption (id, options) {
    for (var i=0, len=options.length; i<len; i++)
    {
        if (options[i].getAttribute('ID') == id) return options[i].getAttribute('Name');
    }
    
    return null;
}

function getItemById (id, items) {
    for (var i=0, len=items.length; i<len; i++)
    {
        if (items[i].getAttribute('ID') == id) return items[i];
    }
    
    return null;
}

function getUserById (id, items) {
    for (var i=0, len=items.length; i<len; i++)
    {
        if (items[i].getAttribute('ID') == id) return items[i];
    }
    
    return null;
}

// function to load task fields when a task is clicked in the list box
var loadedTask = null;
function loadTask() {
    // reset fields first
    //resetTaskFields();

    var listBox = $('assetEditor_Tasks');
    var taskId = listBox.options[listBox.selectedIndex].value;
    var tasks = assetRequest.responseXML.getElementsByTagName('TASK');
    loadedTask = getItemById(taskId, tasks);
    
    // load due date - required field
    var dueDate = parseXMLDate(loadedTask.getAttribute('DueDate'));
    $('assetEditor_TaskDueDate').value = dueDate[1] + "/" + dueDate[2] + "/" + dueDate[0].substr(2);
    var completedDate = parseXMLDate(loadedTask.getAttribute('Completed'));
    
    // load completed date
    if (completedDate) {
        $('assetEditor_TaskCompletedDate').value = completedDate[1] + "/" + completedDate[2] + "/" + completedDate[0].substr(2);
    }
    
    // load who the task is assigned to
    var userList = $('assetEditor_TaskAssignTo');
    var userId = loadedTask.getAttribute('UserID');
    for (i=0, len=userList.options.length; i< len; i++) {
        if (userList.options[i].value == userId) {
            userList.options[i].setAttribute('selected', 'selected');
            userList.selectedIndex = i;
        } else {
            userList.options[i].removeAttribute('selected');
        }
    }
    
    // load the task type
    var taskOptionList = $('assetEditor_TaskType');
    var taskOptionId = loadedTask.getAttribute('TaskOptionID');
    for (i=0, len=taskOptionList.options.length; i< len; i++) {
        if (taskOptionList.options[i].value == taskOptionId) {
            taskOptionList.options[i].setAttribute('selected', 'selected');
            taskOptionList.selectedIndex = i;
        } else {
            taskOptionList.options[i].removeAttribute('selected');
        }
    }
    
    // load description
    var description = $('assetEditor_TaskDescription');
    var descriptionText = loadedTask.getAttribute('Description');
    if (descriptionText) description.value = descriptionText;
    
    // enable buttons
    $('assetEditor_UpdateTask').removeAttribute('disabled');
    $('assetEditor_DeleteTask').removeAttribute('disabled');
}


// function to clear task fields
function resetTaskFields() {
    if (loadedTask) {loadedTask = null;} 
    
    // hide message
    $('assetEditor_TaskMessages').style.display = "none";   
       
    // clear fields
    $('assetEditor_TaskDueDate').value = "";
    $('assetEditor_TaskCompletedDate').value = "";
    var userList = $('assetEditor_TaskAssignTo');
    for (i=0, len=userList.options.length; i< len; i++) {
        if (i == 0) {
            userList.options[i].setAttribute('selected', 'selected');
            userList.selectedIndex = i;
        } else {
            userList.options[i].removeAttribute('selected');
        }
    }
    var taskOptionList = $('assetEditor_TaskType');
    for (i=0, len=taskOptionList.options.length; i< len; i++) {
        if (i == 0) {
            taskOptionList.options[i].setAttribute('selected', 'selected');
            taskOptionList.selectedIndex = i;
        } else {
            taskOptionList.options[i].removeAttribute('selected');
        }
    }
    $('assetEditor_TaskDescription').value = "";
    
    // disable buttons
    $('assetEditor_UpdateTask').setAttribute('disabled', 'disabled');
    $('assetEditor_DeleteTask').setAttribute('disabled', 'disabled');
    
    // remove selection from select box
    $('assetEditor_Tasks').selectedIndex = -1;
}

// function to convert dates to xml format
function ConvertToXMLDate (datetime) {
    if (!datetime) return null;
    
    if (datetime.search('/') != -1) {  // for dates
        var dateSplit = datetime.split('/');
        if (dateSplit[2].length == 2) dateSplit[2] = "20" + dateSplit[2];
        var xmlDate = dateSplit[2] + "-" + parseInt(dateSplit[0],10).toPaddedString(2,10) + "-" + parseInt(dateSplit[1],10).toPaddedString(2,10) + "T00:00:00";
        return xmlDate;
    } else if ( (datetime.search('am') != -1) || (datetime.search('AM') != -1) ) { // for am times
        var timeStrip = datetime.replace(/[am|AM]/,'');
        var timeSplit = timeStrip.split(':');
        var xmlTime = "1900-01-01T" + parseInt(timeSplit[0],10).toPaddedString(2,10) + ":" + parseInt(timeSplit[1],10).toPaddedString(2,10) + ":00";
        return xmlTime;     
    } else if ( (datetime.search('pm') != -1) || (datetime.search('PM') != -1) ) { // for am times
        var timeStrip = datetime.replace(/[pm|PM]/,'');
        var timeSplit = timeStrip.split(':');
        timeSplit[0] = parseInt(timeSplit[0],10) + 12;
        var xmlTime = "1900-01-01T" + parseInt(timeSplit[0],10).toPaddedString(2,10) + ":" + parseInt(timeSplit[1],10).toPaddedString(2,10) + ":00";
        return xmlTime; 
    } else if (datetime.match(durationRegex)) {  // for durations or times without am/pm
        if (datetime.indexOf(':') != -1) {
            var timeSplit = datetime.split(':');
            if (timeSplit.length == 3) {
                var xmlTime = "1900-01-01T" + parseInt(timeSplit[0],10).toPaddedString(2,10) + ":" + parseInt(timeSplit[1],10).toPaddedString(2,10) + ":" + parseInt(timeSplit[2],10).toPaddedString(2,10);
                return xmlTime;
            } else if (timeSplit.length == 2) {
                var xmlTime = "1900-01-01T00:" + parseInt(timeSplit[0],10).toPaddedString(2,10) + ":" + parseInt(timeSplit[1],10).toPaddedString(2,10);
                return xmlTime; 
            }
        } else {
            var xmlTime = "1900-01-01T00:00:" + parseInt(datetime,10).toPaddedString(2,10);
            return xmlTime; 
        }       
    }
}

// function to reset media search form
function resetMediaSearch() {
    $('assetEditor_Search_Filename').value = "";
    $('assetEditor_Search_FileCreationDateFrom').value = "";
    $('assetEditor_Search_FileCreationDateTo').value = "";
}

// function to update number of files in asset based on channel selection
function updateAssetFiles() {
    var channel = $('assetEditor_Channel');
    var mediaInstance = assetRequest.responseXML.getElementsByTagName('MEDIAINSTANCE');
    if (channel.selectedIndex == 0) { //show no files
        $('assetEditor_NoFiles').style.display = "block";
        $('assetEditor_FilesRow').style.display = "none";
    } else if (channel.options[channel.selectedIndex].value == '1') { // Mitsubishi
        // show and hide necessary files
        $('assetEditor_NoFiles').style.display = "none";
        $('assetEditor_FilesRow').style.display = "block";
        $('assetEditor_FileCol1').style.display = "block";
        $('assetEditor_FileCol2').style.display = "none";
        
        // load media 
        //if (mediaInstance[0]) addFileToAsset(mediaInstance[0].childNodes[1], 1);
        if (mediaInstance[0]) addFileToAsset(mediaInstance[0], 1);
    }  else if (channel.options[channel.selectedIndex].value == '2') { // Ribbons
        $('assetEditor_NoFiles').style.display = "none";
        $('assetEditor_FilesRow').style.display = "block";
        $('assetEditor_FileCol1').style.display = "block";
        $('assetEditor_FileCol2').style.display = "block";
        
        // load media 
        //get correct slot
        var mediaPlayer1 = (mediaInstance[0]) ? mediaInstance[0].getAttribute('PlayerID') : null;
        var mediaPlayer2 = (mediaInstance[1]) ? mediaInstance[1].getAttribute('PlayerID') : null;
        
        if ( mediaInstance[0] && (mediaPlayer1 == 2)) {
            addFileToAsset(mediaInstance[0], 1);
        } else if ( mediaInstance[0] && (mediaPlayer1 == 3)) {
            addFileToAsset(mediaInstance[0], 2);
        }
        if ( mediaInstance[1] && (mediaPlayer2 == 2)) {
            addFileToAsset(mediaInstance[1], 1);
        } else if ( mediaInstance[1] && (mediaPlayer2 == 3)) {
            addFileToAsset(mediaInstance[1], 2);
        }
        
    }  else if (channel.options[channel.selectedIndex].value == '3') { // Ticker
        $('assetEditor_NoFiles').style.display = "none";
        $('assetEditor_FilesRow').style.display = "block";
        $('assetEditor_FileCol1').style.display = "block";
        $('assetEditor_FileCol2').style.display = "none";
        
        // load media 
        if (mediaInstance[0]) addFileToAsset(mediaInstance[0], 1);
    }
}

function addFileWrapper (slot) {
    var listBox = $('assetEditorResults');
    var mediaId = listBox.options[listBox.selectedIndex].value;
    var media = searchRequest.responseXML.getElementsByTagName('MEDIA');
    // find the matching media from the id
    var mediaNode = null;
    for (var i=0, len=media.length; i<len; i++) {
        if (mediaId == media[i].getAttribute('ID')) {
            mediaNode = media[i];
            break;
        }
    }
    //var mediaInstanceNode = mediaNode.parentNode;
    
    addFileToAsset(mediaNode, slot);
}

// function to add a file to a slot
function addFileToAsset(mediaInstance, slot) {

    var isMedia = false;
    if (mediaInstance.childNodes.length == 0) isMedia = true;

    if (!mediaInstance) return; 
    
    var containerStr = "assetEditor_File" + slot;
    var fileContainer = $(containerStr);
    
    var media = (isMedia) ? mediaInstance : mediaInstance.childNodes[1];
    
    // fill in hidden fields
    var mediaThumbnailPath = media.getAttribute('ThumbnailJPEG');
    if (mediaThumbnailPath) {
        var thumbnailPath = "AssetThumbnailJPEG\\" + mediaThumbnailPath + ".jpg";
        var thumbnailWidth = assetThumbnailJPEGSizeCfg.split('x')[0] + "px";
        var thumbnailHeight = assetThumbnailJPEGSizeCfg.split('x')[1] + "px";
        fileContainer.style.display = "none";
        var thumbContainer = "assetEditor_Thumb" + slot;
        $(thumbContainer).style.display = "block";
        var thumbnail = document.createElement('img');
        thumbnail.setAttribute('src', thumbnailPath);
        thumbnail.id = "thumbnail_" + slot;
        thumbnail.style.width = thumbnailWidth;
        thumbnail.style.height = thumbnailHeight;
        $(thumbContainer).appendChild(thumbnail);
    } else {
        fileContainer.style.backgroundColor = "#3399ff";
        fileContainer.style.color = "#fff";
        fileContainer.innerHTML = "File Assigned";
    }
    var idLblStr = "assetEditor_FileId" + slot;
    var idLbl = $(idLblStr);
    idLbl.innerHTML = media.getAttribute('ID');
    var vidPathLblStr = "assetEditor_VidPath" + slot;
    var vidPathLbl = $(vidPathLblStr);
    var mediaVidPath = media.getAttribute('ThumbnailVidPath');
    if (mediaVidPath) {
        //var vidPath = "file:///" + assetThumbnailVidPathCfg.replace(/\\/g, '/') + "/" + mediaVidPath + ".mov";
        var vidPath = "AssetThumbnailVid\\" + mediaVidPath + ".mov";
        vidPathLbl.innerHTML = vidPath;
    }
    var heightLblStr = "assetEditor_Height" + slot;
    var heightLbl = $(heightLblStr);
    heightLbl.innerHTML = media.getAttribute('Height');
    var widthLblStr = "assetEditor_Width" + slot;
    var widthLbl = $(widthLblStr);
    widthLbl.innerHTML = media.getAttribute('Width');
    
    // fill in user-visible fields
    var sourcePath = media.getAttribute('SourcePath');
    var ingestedPath = media.getAttribute('IngestedFromPath');
    var fileCount = media.getAttribute('FileCount');
    var ingestedDate = media.getAttribute('CreatedOn');
    var isImageSet = media.getAttribute('IsImageSet');
    
    var srcLblStr = "assetEditor_FileSrc" + slot;
    var srcLbl = $(srcLblStr);
    srcLbl.innerHTML = "Source Path: " + sourcePath;
    
    var ingestedLblStr = "assetEditor_FileIngested" + slot;
    var ingestedLbl = $(ingestedLblStr);
    ingestedLbl.innerHTML = "Ingested From Path: " + ingestedPath;
    
    var fileDurLblStr = "assetEditor_FileDuration" + slot;
    var fileDurLbl = $(fileDurLblStr);
    
    // display files or duration based on rules
    if (sourcePath.strip().search(/M_/i) == 0) {
        if (isImageSet == 1) {
            fileDurLbl.innerHTML = "Image Files: " + fileCount;
        } else {
            var totalSeconds = Math.round(parseInt(fileCount,10)/60);
            var minutes = Math.floor(totalSeconds/60);
            var seconds = totalSeconds % 60;
            var duration = minutes.toPaddedString(2,10) + ":" + seconds.toPaddedString(2,10);
            fileDurLbl.innerHTML = "Duration: " + duration;
        }
    } else if (sourcePath.strip().search(/R_|T_/i) == 0) {
        if (isImageSet == 1) {
            fileDurLbl.innerHTML = "Image Files: " + fileCount;
        } else {
            var totalSeconds = Math.round(parseInt(fileCount,10)/30);
            var minutes = Math.floor(totalSeconds/60);
            var seconds = totalSeconds % 60;
            var duration = minutes.toPaddedString(2,10) + ":" + seconds.toPaddedString(2,10);
            fileDurLbl.innerHTML = "Duration: " + duration;
        }
    } else {
        fileDurLbl.innerHTML = "Image Files: " + fileCount;
    }
    
    if (!isMedia) {
        // get mediainstance values
        var filesPresent = mediaInstance.getAttribute('FilesPresentNN');
        var filesPresentBak = mediaInstance.getAttribute('FilesPresentBackupNN');
        var fullyPresent = mediaInstance.getAttribute('FullyPresentNN');
        var fullyPresentBak = mediaInstance.getAttribute('FullyPresentBackupNN');
        
        var filesPresentLblStr = "assetEditor_FilesPresent" + slot;
        var filesPresentLbl = $(filesPresentLblStr);
        if (filesPresent) filesPresentLbl.innerHTML = "Files Present: " + filesPresent;
        
        var filesPresentBakLblStr = "assetEditor_FilesPresentBak" + slot;
        var filesPresentBakLbl = $(filesPresentBakLblStr);
        if (filesPresentBak) filesPresentBakLbl.innerHTML = "Files Present Backup: " + filesPresentBak;
        
        var fullyPresentLblStr = "assetEditor_FullyPresent" + slot;
        var fullyPresentLbl = $(fullyPresentLblStr);
        if (fullyPresent) {
            var boolStr = (fullyPresent == 1) ? "Yes" : "No";
            fullyPresentLbl.innerHTML = "Fully Present: " + boolStr;
        }
        
        var fullyPresentBakLblStr = "assetEditor_FullyPresentBak" + slot;
        var fullyPresentBakLbl = $(fullyPresentBakLblStr);
        if (fullyPresentBak) {
            var boolStr = (fullyPresent == 1) ? "Yes" : "No";
            fullyPresentBakLbl.innerHTML = "Fully Present Backup: " + boolStr;
        }
    }
    
    // hide add btn, show remove button, and show thumbnail if available
    var addBtnStr = "assetEditor_AddBtn" + slot;
    var previewBtnStr = "assetEditor_PreviewBtn" + slot;
    var removeBtnStr = "assetEditor_RemoveBtn" + slot;
    $(addBtnStr).style.display = "none";
    if (vidPath) $(previewBtnStr).style.display = "block";
    $(removeBtnStr).style.display = "block";
}

// function to show preview of video file
var previewWindows = [];
function showFilePreview(slot) {

    var vidPathLblStr = "assetEditor_VidPath" + slot;
    var vidPathLbl = $(vidPathLblStr);
    var vidPath = vidPathLbl.innerHTML;
    if (vidPath.length < 1) return;
    var width = assetThumbnailVidSizeCfg.split('x')[0] + "px";
    var height = (parseInt(assetThumbnailVidSizeCfg.split('x')[1],10) + 20) + "px";  // plus 20 for controller bar

	// open window to show preview
	var win = null;
    var htmlHeader = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
    htmlHeader += '<html xmlns="http://www.w3.org/1999/xhtml" >';
    htmlHeader += '<head>';
    htmlHeader += '<title>Preview Video</title>';
    htmlHeader += '<link href="StyleSheet.css" rel="stylesheet" type="text/css" />';
    htmlHeader += '</head>';
    htmlHeader += '<body><center>';
    
    var windowWidth = (parseInt(assetThumbnailVidSizeCfg.split('x')[0],10) + 100) + "px";
    var windowHeight = (parseInt(assetThumbnailVidSizeCfg.split('x')[1],10) + 120) + "px";
    var leftOffset = (parseInt(assetThumbnailVidSizeCfg.split('x')[0],10) + 106) + "px";
    if (slot == 1) win = window.open('', '_blank', 'left=0, scrollbars=1, resizable=1, width=' + windowWidth + ', height=' + windowHeight + '');
    if (slot == 2) win = window.open('', '_blank', 'left=' + leftOffset + ', scrollbars=1, resizable=1, width=' + windowWidth + ', height=' + windowHeight + '');
    win.document.write(htmlHeader);
    win.document.write('<br /><br /><br /><br />');
    win.document.write('<embed src="' + vidPath + '" width="' + width + '" height="' + height + '" autoplay="true" loop="false" controller="true" pluginspage="http://www.apple.com/quicktime/"></embed>');
    win.document.write('</center></body></html>');
    win.document.close();
    previewWindows[slot] = win;
    if (previewWindows[1] != null) previewWindows[1].focus();
    if (previewWindows[2] != null) previewWindows[2].focus();
    //win.focus();	    
}

// function to remove a file from an asset
function removeFileFromAsset(slot) {
    var containerStr = "assetEditor_File" + slot;
    var fileContainer = $(containerStr);
    fileContainer.style.backgroundColor = "";
    fileContainer.style.color = "#666";
    fileContainer.innerHTML = "No File";
    fileContainer.style.display = "block";
    var idLblStr = "assetEditor_FileId" + slot;
    var idLbl = $(idLblStr);
    idLbl.innerHTML = "";
    var vidPathLblStr = "assetEditor_VidPath" + slot;
    var vidPathLbl = $(vidPathLblStr);
    vidPathLbl.innerHTML = "";
    var heightLblStr = "assetEditor_Height" + slot;
    var heightLbl = $(heightLblStr);
    heightLbl.innerHTML = "";
    var widthLblStr = "assetEditor_Width" + slot;
    var widthLbl = $(widthLblStr);
    widthLbl.innerHTML = "";
    
    // empty visible strings
    var srcLblStr = "assetEditor_FileSrc" + slot;
    var srcLbl = $(srcLblStr);
    srcLbl.innerHTML = "";
    
    var ingestedLblStr = "assetEditor_FileIngested" + slot;
    var ingestedLbl = $(ingestedLblStr);
    ingestedLbl.innerHTML = "";
    
    var fileDurLblStr = "assetEditor_FileDuration" + slot;
    var fileDurLbl = $(fileDurLblStr);
    fileDurLbl.innerHTML = "";
    
    var filesPresentLblStr = "assetEditor_FilesPresent" + slot;
    var filesPresentLbl = $(filesPresentLblStr);
    filesPresentLbl.innerHTML = "";
    
    var filesPresentBakLblStr = "assetEditor_FilesPresentBak" + slot;
    var filesPresentBakLbl = $(filesPresentBakLblStr);
    filesPresentBakLbl.innerHTML = "";
    
    var fullyPresentLblStr = "assetEditor_FullyPresent" + slot;
    var fullyPresentLbl = $(fullyPresentLblStr);
    fullyPresentLbl.innerHTML = "";
    
    var fullyPresentBakLblStr = "assetEditor_FullyPresentBak" + slot;
    var fullyPresentBakLbl = $(fullyPresentBakLblStr);
    fullyPresentBakLbl.innerHTML = "";
    
    // reset buttons and thumbnail
    var thumbContainer = "assetEditor_Thumb" + slot;
    var addBtnStr = "assetEditor_AddBtn" + slot;
    var previewBtnStr = "assetEditor_PreviewBtn" + slot;
    var removeBtnStr = "assetEditor_RemoveBtn" + slot;
    if ($(thumbContainer).firstDescendant()) $(thumbContainer).firstDescendant().remove();
    $(thumbContainer).style.display = "none";
    $(addBtnStr).style.display = "block";
    $(previewBtnStr).style.display = "none";
    $(removeBtnStr).style.display = "none";
}

// function to sort tasks
function sortTasks() {
    // get task select list
    var sortList = $('assetEditor_TaskSort');
    var selectList = $('assetEditor_Tasks');
    if (selectList.options.length == 0) return;
    // get selected value
    var selectedSortValue = sortList.options[sortList.selectedIndex].value;
    var tasks = assetRequest.responseXML.getElementsByTagName('TASK');
    var userNodes = assetRequest.responseXML.getElementsByTagName('USER');
    var taskTypeNodes = assetRequest.responseXML.getElementsByTagName('TASKOPTION');
    var taskIds = [];
    var users = [];
    var usersSorted = [];
    var dueDates = [];
    var dueDatesSorted = [];
    var taskTypes = [];
    var taskTypesSorted = [];
    var userList = $('assetEditor_TaskAssignTo');
    var taskTypeList = $('assetEditor_TaskType');
    // add task attributes to all arrays
    for (var i=0, len=tasks.length; i<len; i++) {
        var user = getUserById(tasks[i].getAttribute('UserID'), userNodes).getAttribute('UserName');
        var taskType = getItemById(tasks[i].getAttribute('TaskOptionID'), taskTypeNodes).getAttribute('Name');
        var dueDate = tasks[i].getAttribute('DueDate');
        var taskId = tasks[i].getAttribute('ID');
        taskIds.push(taskId);
        users.push(user);
        usersSorted.push(user);
        dueDates.push(dueDate);
        dueDatesSorted.push(dueDate);
        taskTypes.push(taskType);
        taskTypesSorted.push(taskType);
    }
    if (selectedSortValue == 1) { // sort by earliest due date
        // remove current elements
        var options = selectList.immediateDescendants();
        for (var i=0, len=options.length; i<len; i++) {
            options[i].remove();
        }
        // sort array and add options back
        dueDatesSorted.sort();
        for (var i=0, len=dueDates.length; i<len; i++) {
            var optionEl = document.createElement('option');
            var dueDateText = dueDatesSorted[i];
            var index = dueDates.indexOf(dueDateText);
            optionEl.text = taskTypes[index] + " (" + users[index] + ")";
            optionEl.value = taskIds[index];
            //optionEl.value = parseInt(i,10) + 1;
            selectList.options.add(optionEl);
        }
        selectList.selectedIndex = -1;
        resetTaskFields();
    } else if (selectedSortValue == 2) { // sort by username
        // remove current elements
        var options = selectList.immediateDescendants();
        for (var i=0, len=options.length; i<len; i++) {
            options[i].remove();
        }
        // sort array and add options back
        usersSorted.sort();
        for (var i=0, len=dueDates.length; i<len; i++) {
            var optionEl = document.createElement('option');
            var userText = usersSorted[i];
            var index = users.indexOf(userText);
            optionEl.text = taskTypes[index] + " (" + users[index] + ")";
            optionEl.value = taskIds[index];
            //optionEl.value = parseInt(i,10) + 1;
            selectList.options.add(optionEl);
        }    
        selectList.selectedIndex = -1;
        resetTaskFields();
    } else if (selectedSortValue == 3) { // sort by task type
        // remove current elements
        var options = selectList.immediateDescendants();
        for (var i=0, len=options.length; i<len; i++) {
            options[i].remove();
        }
        // sort array and add options back
        taskTypesSorted.sort();
        for (var i=0, len=dueDates.length; i<len; i++) {
            var optionEl = document.createElement('option');
            var taskTypeText = taskTypesSorted[i];
            var index = taskTypes.indexOf(taskTypeText);
            optionEl.text = taskTypes[index] + " (" + users[index] + ")";
            optionEl.value = taskIds[index];
            //optionEl.value = parseInt(i,10) + 1;
            selectList.options.add(optionEl);
        }    
        selectList.selectedIndex = -1;
        resetTaskFields();
    }
}

// function to validate task fields
function validateTask() {
    var msgNode = $('assetEditor_TaskMessages');
    var errMsg = "";
    
    // clear message node
    msgNode.style.display = "none";
    msgNode.innerHTML = "";
    msgNode.style.color = "";
    
    // check required fields
    if ($('assetEditor_TaskDueDate').value.strip() == '') 
        errMsg += "&#149; Task Due Date is a required field<br />";
    if ($('assetEditor_TaskAssignTo').selectedIndex == 0) 
        errMsg += "&#149; Assign To is a required field<br />";
    if ($('assetEditor_TaskType').selectedIndex == 0) 
        errMsg += "&#149; Task Type is a required field<br />";
    
    // stop and alert if errors
    if (errMsg != '') {
        msgNode.innerHTML = errMsg;
        msgNode.style.color = "#f00";
        msgNode.style.display = "block";
        return false;
    }
    
    // validate date fields
    if (($('assetEditor_TaskDueDate').value.strip() != '') && !($('assetEditor_TaskDueDate').value.strip().match(dateRegex)))
            errMsg += "&#149; Task Due Date is not formatted correctly<br />";
    if (($('assetEditor_TaskCompletedDate').value.strip() != '') && !($('assetEditor_TaskCompletedDate').value.strip().match(dateRegex)))
            errMsg += "&#149; Task Completed Date is not formatted correctly<br />";
            
    // stop and alert if errors
    if (errMsg != '') {
        msgNode.innerHTML = errMsg;
        msgNode.style.color = "#f00";
        msgNode.style.display = "block";
        return false;
    }
    
    // success
    return true;

}

// function to add a new task
function addTask() {
    if (validateTask()) {
        var newTaskId = 0;
        var tasks = assetRequest.responseXML.getElementsByTagName('TASK');
        // get new task index
        for (var i=0, len=tasks.length; i<len; i++) {
            if (tasks[i].getAttribute('ID') > newTaskId) {
                newTaskId = tasks[i].getAttribute('ID')
            }
        }
        newTaskId++;    
        
        var asset = assetRequest.responseXML.getElementsByTagName('ASSET');
       
        // get values
        var dueDate = ConvertToXMLDate($('assetEditor_TaskDueDate').value);
        var completedDate = $('assetEditor_TaskCompletedDate').value;
        if (completedDate) completedDate = ConvertToXMLDate(completedDate);
        var userList = $('assetEditor_TaskAssignTo');
        var userId = userList.options[userList.selectedIndex].value;
        var userName = userList.options[userList.selectedIndex].text;
        var taskOptionList = $('assetEditor_TaskType');
        var taskOptionId = taskOptionList.options[taskOptionList.selectedIndex].value;
        var description = $('assetEditor_TaskDescription').value;
        
        // create new task node and set attributes
        var newTask = assetRequest.responseXML.createElement('TASK');
        // task id
        var IdAtt = assetRequest.responseXML.createAttribute('ID');
        IdAtt.value = newTaskId;
        newTask.setAttributeNode(IdAtt); 
        // asset id
        var assetIdAtt = assetRequest.responseXML.createAttribute('AssetID');
        assetIdAtt.value = asset[0].getAttribute('ID');
        newTask.setAttributeNode(assetIdAtt); 
        // user id
        var userIdAtt = assetRequest.responseXML.createAttribute('UserID');
        userIdAtt.value = userId;
        newTask.setAttributeNode(userIdAtt); 
        // due date
        var dueDateAtt = assetRequest.responseXML.createAttribute('DueDate');
        dueDateAtt.value = dueDate;
        newTask.setAttributeNode(dueDateAtt); 
        // description
        if (description != '') {
            var descriptionAtt = assetRequest.responseXML.createAttribute('Description');
            descriptionAtt.value = description;
            newTask.setAttributeNode(descriptionAtt); 
        }
        // task option
        var taskOptionAtt = assetRequest.responseXML.createAttribute('TaskOptionID');
        taskOptionAtt.value = taskOptionId;
        newTask.setAttributeNode(taskOptionAtt); 
        // completed date
        if (completedDate != '') {
            var completedDateAtt = assetRequest.responseXML.createAttribute('Completed');
            completedDateAtt.value = completedDate;
            newTask.setAttributeNode(completedDateAtt); 
        }

        // append new task to end of asset node
        asset[0].appendChild(newTask);
        
        // add new task to end of list box
        var listBox = $('assetEditor_Tasks');
        var optionEl = document.createElement('option');
        var taskOptionList = $('assetEditor_TaskType');
        var taskOptionText = taskOptionList.options[taskOptionList.selectedIndex].text + " (" + userName + ")";
        optionEl.text = taskOptionText;
        optionEl.value = newTaskId;
        //optionEl.value = parseInt(listBox.options.length,10) + 1;
        listBox.options.add(optionEl);

        listBox.selectedIndex = listBox.options.length-1;
        
        loadedTask = newTask;
        
        // show success message
        var message = $('assetEditor_TaskMessages');
        message.innerHTML = "Task added";
        message.style.color = "Green";
        message.style.display = "block";
        
       setPageModified(true);
       
       // enable buttons
        $('assetEditor_UpdateTask').removeAttribute('disabled');
        $('assetEditor_DeleteTask').removeAttribute('disabled');
    }
}

// function to update a loaded task
function updateTask() {
    if (!loadedTask) return;
    if (validateTask()) {
        var asset = assetRequest.responseXML.getElementsByTagName('ASSET');
       
        // get values
        var dueDate = ConvertToXMLDate($('assetEditor_TaskDueDate').value);
        var completedDate = $('assetEditor_TaskCompletedDate').value;
        if (completedDate) completedDate = ConvertToXMLDate(completedDate);
        var userList = $('assetEditor_TaskAssignTo');
        var userId = userList.options[userList.selectedIndex].value;
        var userName = userList.options[userList.selectedIndex].text;
        var taskOptionList = $('assetEditor_TaskType');
        var taskOptionId = taskOptionList.options[taskOptionList.selectedIndex].value;
        var description = $('assetEditor_TaskDescription').value;
        
        loadedTask.setAttribute('AssetID', asset[0].getAttribute('ID'));
        loadedTask.setAttribute('UserID', userId);
        loadedTask.setAttribute('DueDate', dueDate);
        if (description != '') loadedTask.setAttribute('Description', description);
        loadedTask.setAttribute('TaskOptionID', taskOptionId);
        if (completedDate != '') loadedTask.setAttribute('Completed', completedDate);
        //alert(assetRequest.responseXML.xml);
        
        // update selected listbox item
        var listBox = $('assetEditor_Tasks');
        listBox.options[listBox.selectedIndex].text = taskOptionList.options[taskOptionList.selectedIndex].text + " (" + userName + ")";
        
        // show success message
        var message = $('assetEditor_TaskMessages');
        message.innerHTML = "Task updated";
        message.style.color = "Green";
        message.style.display = "block";
        
        setPageModified(true);
    }
}

// function to delete a task from the list
function deleteTask() {
    if (!loadedTask) return;
    // delete loadedTask node
    var id = loadedTask.getAttribute('ID');
    var asset = assetRequest.responseXML.getElementsByTagName('ASSET')[0];
    asset.removeChild(loadedTask);
    
    // remove from list box
    var listBox = $('assetEditor_Tasks');
    //var taskId = listBox.options[listBox.selectedIndex].remove();
    listBox.options[listBox.selectedIndex].remove();
    listBox.selectedIndex = -1;
    
    resetTaskFields();
    
    // show success message
    var message = $('assetEditor_TaskMessages');
    message.innerHTML = "Task deleted";
    message.style.color = "Green";
    message.style.display = "block";
    
    setPageModified(true);
}

function setDrillParams() {
    var selectedEl = activeEditor.selectedCell
    var drillType = (selectedEl) ? "Edit" : "New"; // this is a "new" drilldown
    
    if (drillType == "Edit") {
        if (activeEditor.systemLevel < 3)
            if (selectedEl.match('div')) selectedEl = selectedEl.firstDescendant();
        var peca = activeEditor.getPeca(selectedEl)
    }
    
    if (activeEditor.systemLevel == 0) {  // drill down to package
        if (drillType == "Edit") {
            var selectedList = null;
            var selectedDrop = null;
            if (selectedEl.match('div')) {
                selectedList = selectedEl.parentNode.parentNode;
                selectedDrop = selectedEl.parentNode;
            } else {
                selectedList = selectedEl.parentNode;
            }
            packageEditorPackageId = peca.dbId;
            var listNum = parseInt(selectedList.id.split('_')[3],10);
            var rowIndex = parseInt(selectedDrop.id.substr(selectedDrop.id.indexOf('drop_') + 5),10);
            packageEditorPackageDate = activeEditor.listLookupIds[listNum];
            packageEditorPackageTime = activeEditor.timeSlots[rowIndex];
            packageEditorPecaEl = selectedEl;
            if (scheduleEditorIsModified > 0) {
                scheduleEditorDrillHeader = "Schedule: " + activeEditor.headerText[listNum] + "* > ";
            } else {
                scheduleEditorDrillHeader = "Schedule: " + activeEditor.headerText[listNum] + " > ";
            }
            //$('packageEditor_SaveCopy').style.display = "none";
        } else {
            packageEditorPackageId = -1;
            packageEditorPackageDate = "";
            packageEditorPackageTime = "";
            packageEditorPecaEl = null;
            if (scheduleEditorIsModified > 0) {
                scheduleEditorDrillHeader = "Schedule: " + activeEditor.headerText[listNum] + "* > ";
            } else {
                scheduleEditorDrillHeader = "Schedule: " + activeEditor.headerText[listNum] + " > ";
            }
//            if (scheduleEditorIsModified > 0) {
//                scheduleEditorDrillHeader = "Schedule* > ";
//            } else {
//                scheduleEditorDrillHeader = "Schedule > ";
//            }
            //$('packageEditor_SaveCopy').style.display = "none";        
        }
    } else if (activeEditor.systemLevel == 1) { // drill down to event
        if (drillType == "Edit") {
            eventEditorEventId = peca.dbId;
            if (packageEditorIsModified > 0) {
                packageEditorDrillHeader = scheduleEditorDrillHeader + "Package: " + $('packageEditor_Name').value.strip() + "* > ";
            } else {
                packageEditorDrillHeader = scheduleEditorDrillHeader + "Package: " + $('packageEditor_Name').value.strip() + " > ";
            }
            //$('eventEditor_SaveCopy').style.display = "none";   
        } else {
            eventEditorEventId = -1;
//            if (packageEditorIsModified > 0) {
//                packageEditorDrillHeader = scheduleEditorDrillHeader + "Package* > ";
//            } else {
//                packageEditorDrillHeader = scheduleEditorDrillHeader + "Package > ";
//            }
            var packageHeaderName = ($('packageEditor_Name').value.strip().length > 0) ? $('packageEditor_Name').value.strip() : "(new package)";
            if (packageEditorIsModified > 0) {
                packageEditorDrillHeader = scheduleEditorDrillHeader + "Package: " + packageHeaderName + "* > ";
            } else {
                packageEditorDrillHeader = scheduleEditorDrillHeader + "Package: " + packageHeaderName + " > ";
            }
            //$('eventEditor_SaveCopy').style.display = "none";   
        }
    } else if (activeEditor.systemLevel == 2) { // drill down to asset or combo
        if (drillType == "Edit") {
            if (eventEditorIsModified > 0) {
                eventEditorDrillHeader = packageEditorDrillHeader + "Event: " + $('eventEditor_Name').value.strip() + "* > ";
            } else {
                eventEditorDrillHeader = packageEditorDrillHeader + "Event: " + $('eventEditor_Name').value.strip() + " > ";
            }     
            if (peca.isCombo == 1) {
                comboEditorComboId = peca.dbId;
                //$('comboEditor_SaveCopy').style.display = "none";
            } else {
                assetEditorAssetId = peca.dbId; 
                //$('assetEditor_SaveCopy').style.display = "none";                 
            }
        } else {
            var eventHeaderName = ($('eventEditor_Name').value.strip().length > 0) ? $('eventEditor_Name').value.strip() : "(new event)";
            if (eventEditorIsModified > 0) {
                eventEditorDrillHeader = packageEditorDrillHeader + "Event: " + eventHeaderName + "* > ";
            } else {
                eventEditorDrillHeader = packageEditorDrillHeader + "Event: " + eventHeaderName + " > ";
            }   
//            if (eventEditorIsModified > 0) {
//                eventEditorDrillHeader = packageEditorDrillHeader + "Event* > ";
//            } else {
//                eventEditorDrillHeader = packageEditorDrillHeader + "Event > ";
//            }     
            comboEditorComboId = -1;
            assetEditorAssetId = -1;               
        }
    } else if (activeEditor.systemLevel == 3) { // drill down to asset
        if (drillType == "Edit") {
            assetEditorAssetId = peca.dbId;
            if (comboEditorIsModified > 0) {
                comboEditorDrillHeader = eventEditorDrillHeader + "Combo: " + $('comboEditor_Name').value.strip() + "* > ";
            } else {
                comboEditorDrillHeader = eventEditorDrillHeader + "Combo: " + $('comboEditor_Name').value.strip() + " > ";
            }  
            //$('assetEditor_SaveCopy').style.display = "none";
        } else {
            assetEditorAssetId = -1;
            var comboHeaderName = ($('comboEditor_Name').value.strip().length > 0) ? $('comboEditor_Name').value.strip() : "(new combo)";
            if (comboEditorIsModified > 0) {
                comboEditorDrillHeader = eventEditorDrillHeader + "Combo: " + comboHeaderName + "* > ";
            } else {
                comboEditorDrillHeader = eventEditorDrillHeader + "Combo: " + comboHeaderName + " > ";
            }  
//            if (comboEditorIsModified > 0) {
//                comboEditorDrillHeader = eventEditorDrillHeader + "Combo* > ";
//            } else {
//                comboEditorDrillHeader = eventEditorDrillHeader + "Combo > ";
//            }  
        }
    } 
}

// function to drill down one level
function drillDown(level) {
    hideHotKeys();
    $('exportCSVPopup').style.display = "none";
    setDrillParams();
    var selectedEl = activeEditor.selectedCell
    var drillType = (selectedEl) ? "Edit" : "New"; // this is a "new" drilldown

    // deactivate current editor
    if (activeEditor) {
        activeEditor.deactivateDD();
    }
    // hide current editor (this value is set initially on Editor.aspx)
    $(activeEditorPageId).style.display = "none";

    // check level and adjust header and return button (no level 0 for drilldown); then load appropriate page
    if (level == 1) {  // package editor
        packageEditorReturnButton.value = "Return to Schedules";
        packageEditorReturnButton.setAttribute('onclick','checkReturn(this,"");');
        packageEditorCancelButton.setAttribute('onclick','checkReturn(this,"");');
        $('packageEditor_SaveCopy').style.display = "none";
        $('packageEditorCreateNew').style.display = "none"
        activeEditorPageId = "packageEditor";
        applyUserAccess('Editor');
        $(activeEditorPageId).style.display = "block";
        packageEditorEditChoice = drillType;
        loadPackageEditor();
    } else if (level == 2) {  // event editor
        eventEditorReturnButton.value = "Return to Packages";
        eventEditorReturnButton.setAttribute('onclick','checkReturn(this,"");');
        eventEditorCancelButton.setAttribute('onclick','checkReturn(this,"");');
        $('eventEditor_SaveCopy').style.display = "none";
        $('eventEditorCreateNew').style.display = "none"
        activeEditorPageId = "eventEditor";
        applyUserAccess('Editor');
        $(activeEditorPageId).style.display = "block";
        eventEditorEditChoice = drillType;
        loadEventEditor();
    } else if (level == 3) {  // combo editor
        comboEditorReturnButton.value = "Return to Events";
        //comboEditorEditChoice = "Edit"
        comboEditorReturnButton.setAttribute('onclick','checkReturn(this,"");');
        comboEditorCancelButton.setAttribute('onclick','checkReturn(this,"");');
        $('comboEditor_SaveCopy').style.display = "none";
        $('comboEditorCreateNew').style.display = "none"
        activeEditorPageId = "comboEditor";
        applyUserAccess('Editor');
        $(activeEditorPageId).style.display = "block";
        comboEditorEditChoice = drillType;
        loadComboEditor();
    } else if (level == 4) {  // asset editor
        //assetEditorReturnButton.value = (editors.length == 3) ? "Return to Events" : "Return to Combos";
        if (activeEditorPageId == "eventEditor") {
            assetEditorReturnButton.value = "Return to Events";
            assetEditorReturnChoice = "Events";
        } else {
            assetEditorReturnButton.value = "Return to Combos";
            assetEditorReturnChoice = "Combos";
        }
        //assetEditorEditChoice = "Edit"
        assetEditorReturnButton.setAttribute('onclick','checkReturn(this,"");');
        assetEditorCancelButton.setAttribute('onclick','checkReturn(this,"");');
        $('assetEditor_SaveCopy').style.display = "none";
        $('assetEditorCreateNew').style.display = "none";
        activeEditorPageId = "assetEditor";
        applyUserAccess('Editor');
        $(activeEditorPageId).style.display = "block";
        assetEditorEditChoice = drillType;
        loadAssetEditor();
    }
}

// function to drill up one level (must save or cancel changes)
function drillUp(level) {
    // hide hot keys
    hideHotKeys();
    $('exportCSVPopup').style.display = "none";

    // close the open object
    objForEditClose();

    // destroy active editor (this removes the editor from the editor array)
    activeEditor.destroy();
    
    // destroy search fields
    if (activeEditorPageId != 'assetEditor') {
        var sfContainerStr = activeEditorPageId + "_SearchFields";
    //    resetSearchFields(sfContainerStr);
        var searchFields = $(sfContainerStr).immediateDescendants();
        for (var i=0, len=searchFields.length; i<len; i++) {
            searchFields[i].remove();
        }
    }

    // clear results box
    clearSearchResults();
    
    // hide current editor
    $(activeEditorPageId).style.display = "none";

    // check level and adjust header and return button
    var hkBaseStr = "";
    if (level == 0) {
        resetPackagePage();
        activeEditorPageId = "scheduleEditor";
        hkBaseStr = "event_HK";
        sfXML = scheduleSFXML;
    } else if (level == 1) {
        resetEventPage();
        activeEditorPageId = "packageEditor";
        hkBaseStr = "combo_HK";
        sfXML = packageSFXML;
    } else if (level == 2) {
        if (assetEditorReturnChoice == "Events") {
            resetAssetPage();
        } else { // assetEditorReturnChoice should be blank
            resetComboPage();
        }
        activeEditorPageId = "eventEditor";
        sfXML = eventSFXML;
    } else if (level == 3) {
        resetAssetPage();
        activeEditorPageId = "comboEditor";
        sfXML = comboSFXML;
    } else if (level == 4) {
        activeEditorPageId = "assetEditor";
    }

    // remove hot key selections from previous page hot keys palette
    if (hkBaseStr != '') {
        for (var i=1; i<=5; i++) {
            var hkId = hkBaseStr + i;
            $(hkId).style.backgroundColor = "#fff";
            $(hkId).style.color = "#252525";
            $(hkId).innerHTML = "Empty"
        }
    }

    // show current editor
    $(activeEditorPageId).style.display = "block";

    // update to editor one level up and then activate new editor
    activeEditor = editors.last();
    activeEditor.activateDD();
}

var createNewFlag = false;
// function to create new object on current level (similar to drillup and then drill down)
function createNew() {
    // check for unsaved changes
    if (activeEditorPageId == 'packageEditor') {
        if (packageEditorIsModified > 0) {
            createNewFlag = true;
            //activeReturnHref = "PackageList.aspx";
            $('unsavedChangesAlert').style.display = "block";
            return;
	    }
    } else if (activeEditorPageId == 'eventEditor') {
        if (eventEditorIsModified > 0) {
            createNewFlag = true;
            //activeReturnHref = "EventList.aspx";
            $('unsavedChangesAlert').style.display = "block";
            return;
	    }
    } else if (activeEditorPageId == 'comboEditor') {
        if (comboEditorIsModified > 0) {
            createNewFlag = true;
            //activeReturnHref = "ComboList.aspx";
            $('unsavedChangesAlert').style.display = "block";
            return;
	    }
    } else if (activeEditorPageId == 'assetEditor') {
        if (assetEditorIsModified > 0) {
            createNewFlag = true;
            //activeReturnHref = "";
            $('unsavedChangesAlert').style.display = "block";
            return;
	    }
    }
    
    // if no unsaved changes then proceed
    
    // hide hot keys
    hideHotKeys();
    // hide export if showing
    $('exportCSVPopup').style.display = "none";

    // close the open object
    objForEditClose();

    // destroy active editor (this removes the editor from the editor array)
    activeEditor.destroy();
    
    // destroy search fields
    if (activeEditorPageId != 'assetEditor') {
        var sfContainerStr = activeEditorPageId + "_SearchFields";
        var searchFields = $(sfContainerStr).immediateDescendants();
        for (var i=0, len=searchFields.length; i<len; i++) {
            searchFields[i].remove();
        }
    }

    // clear results box
    //clearSearchResults();
    
    // check level and adjust header and return button
    var hkBaseStr = "";
    if (activeEditorPageId == 'packageEditor') {
        resetPackagePage();
        hkBaseStr = "event_HK";
    } else if (activeEditorPageId == 'eventEditor') {
        resetEventPage();
        hkBaseStr = "combo_HK";
    } else if (activeEditorPageId == 'comboEditor') {
        resetComboPage();
    } else if (activeEditorPageId == 'assetEditor') {
        resetAssetPage();
    }

    // remove hot key selections from previous page hot keys palette
    if (hkBaseStr != '') {
        for (var i=1; i<=5; i++) {
            var hkId = hkBaseStr + i;
            $(hkId).style.backgroundColor = "#fff";
            $(hkId).style.color = "#252525";
            $(hkId).innerHTML = "Empty"
        }
    }

    //setDrillParams(); - take code from here?
    
    //var selectedEl = activeEditor.selectedCell
    var drillType = "New"; // this is a "new" drilldown

    // check level and adjust header and return button (no level 0 for drilldown); then load appropriate page
    if (activeEditorPageId == 'packageEditor') {  // package editor
//        packageEditorReturnButton.value = "Return to Schedules";
//        packageEditorReturnButton.setAttribute('onclick','checkReturn(this,"");');
//        packageEditorCancelButton.setAttribute('onclick','checkReturn(this,"");');
//        $('packageEditor_SaveCopy').style.display = "none";
//        activeEditorPageId = "packageEditor";
//        applyUserAccess('Editor');
//        $(activeEditorPageId).style.display = "block";
        packageEditorPackageId = -1;
        packageEditorEditChoice = "New";
        loadPackageEditor();
    } else if (activeEditorPageId == 'eventEditor') {  // event editor
//        eventEditorReturnButton.value = "Return to Packages";
//        eventEditorReturnButton.setAttribute('onclick','checkReturn(this,"");');
//        eventEditorCancelButton.setAttribute('onclick','checkReturn(this,"");');
//        $('eventEditor_SaveCopy').style.display = "none";
//        activeEditorPageId = "eventEditor";
//        applyUserAccess('Editor');
//        $(activeEditorPageId).style.display = "block";
        eventEditorEventId = -1;
        eventEditorEditChoice = "New";
        loadEventEditor();
    } else if (activeEditorPageId == 'comboEditor') {  // combo editor
//        comboEditorReturnButton.value = "Return to Events";
//        //comboEditorEditChoice = "Edit"
//        comboEditorReturnButton.setAttribute('onclick','checkReturn(this,"");');
//        comboEditorCancelButton.setAttribute('onclick','checkReturn(this,"");');
//        $('comboEditor_SaveCopy').style.display = "none";
//        activeEditorPageId = "comboEditor";
//        applyUserAccess('Editor');
//        $(activeEditorPageId).style.display = "block";
        comboEditorComboId = -1;
        comboEditorEditChoice = "New";
        loadComboEditor();
    } else if (activeEditorPageId == 'assetEditor') {  // asset editor
        //assetEditorReturnButton.value = (editors.length == 3) ? "Return to Events" : "Return to Combos";
//        if (activeEditorPageId == "eventEditor") {
//            assetEditorReturnButton.value = "Return to Events";
//            assetEditorReturnChoice = "Events";
//        } else {
//            assetEditorReturnButton.value = "Return to Combos";
//            assetEditorReturnChoice = "Combos";
//        }
//        //assetEditorEditChoice = "Edit"
//        assetEditorReturnButton.setAttribute('onclick','checkReturn(this,"");');
//        assetEditorCancelButton.setAttribute('onclick','checkReturn(this,"");');
//        $('assetEditor_SaveCopy').style.display = "none";
//        activeEditorPageId = "assetEditor";
//        applyUserAccess('Editor');
//        $(activeEditorPageId).style.display = "block";
        assetEditorAssetId = -1;
        assetEditorEditChoice = "New";
        loadAssetEditor();
    }
}

// function to load a selected package into the live control editor
function liveControlLoadPackage() {

    // get package to load
    var listBox = $('liveControlPackageResults');
    packageId = listBox.options[listBox.selectedIndex].value;
    
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetPackage\" ID=\"" + packageId + "\" />";
    var request = new XMLHttpRequest();
    // create xml and make request
    var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
    xmlStr += "<ROOT>";
    xmlStr += sProc;
    xmlStr += "</ROOT>";
    url = "AjaxPost.aspx";
    request.open('POST', url, false);
    request.setRequestHeader("Content-Type", "text/xml");
    request.send(xmlStr);
    
    // handle response
	if (request.readyState == 4) {
	    if (request.status == 200) {
	        if (request.responseXML != null) {
                // clear results box
                clearSearchResults();
                
                // destroy active editor (this removes the editor from the editor array)
                activeEditor.destroy();
                
                // set up params for drag drop editor
                var headerText = ['LIVE CONTROL'];
                var startTime = new Date(0);
                startTime.setHours(0);
                startTime.setMinutes(0);
                startTime.setSeconds(0);
                var endTime = new Date(0);
                endTime.setHours(0);
                endTime.setMinutes(30);
                endTime.setSeconds(0);
                var listLookupIds = [1];
                
                // load and render drag drop editor
                var ddEditor_Package_0 = new DragDropEditor();
                ddEditor_Package_0.load(1, 'liveControlDDEditorContainer', 1, [1], headerText, packageId, listLookupIds, 
                                            startTime, endTime, 15, 1, 880, 18, 55, 15, 5, request.responseXML);
                ddEditor_Package_0.render();
                ddEditor_Package_0.activateDD();
                
                // change editor lookup id for save
                activeEditor.editorLookupId = liveControlPackageId;
                
                // update search options
                loadLiveControlEventSearch();
	        }
	    }
    } 
}

// function to go to next week of schedules
function loadNextWeek() {
	if (scheduleEditorIsModified > 0) {
	    $('unsavedChangesAlert').style.display = "block";
	    scheduleEditorNextWeek = true;
	    return;
	}

    // hide hot keys
    //hideHotKeys();

    // show loading msg
    $('pageContainer').addClassName('fadedBG');
	$('loadingMsg').style.display = "block";

    // destroy active editor (this removes the editor from the editor array)
    activeEditor.destroy();
    
    // clear results box
    clearSearchResults();

    // load new editor params
    var numCols = 7;
    
    // get types of lists (in this case all slotted)
    var listTypes = [];
    for (var i=0; i<numCols; i++) {
        listTypes[i] = 0;
    }
    
    // update list lookup ids
    var prevDates = scheduleEditorListLookupIds;
    for (var i=0; i<7; i++) {
        var newDate = new Date(prevDates[i]);
        newDate.setDate(newDate.getDate() + 7);  // add 7 days
        var newMonth = parseInt((newDate.getMonth()+1),10).toPaddedString(2,10);
        var newDay = parseInt(newDate.getDate(),10).toPaddedString(2,10);
        var newYear = newDate.getFullYear();
        scheduleEditorListLookupIds[i] = newMonth + "/" + newDay + "/" + newYear;
        scheduleEditorHeaders[i] = scheduleEditorHeaders[i].substring(0,4);        
        scheduleEditorHeaders[i] += newMonth + "/" + newDay;
    }
    
    var startDateSplit = scheduleEditorListLookupIds[0].split("/");
    var startDate = startDateSplit[0] + "/" + startDateSplit[1] + "/" + startDateSplit[2].substr(2);
    var endDateSplit = scheduleEditorListLookupIds[6].split("/");
    var endDate = endDateSplit[0] + "/" + endDateSplit[1] + "/" + endDateSplit[2].substr(2);
    
    scheduleEditorHeader.innerHTML = "Schedules: Week of " + startDate + " - " + endDate;
    
    // get start and end times (in this case 24 hour day with 30 min increments)
    var startTime = new Date(0);
    startTime.setHours(0);
    startTime.setMinutes(0);
    startTime.setSeconds(0);
    var endTime = new Date(0);
    endTime.setHours(24);
    endTime.setMinutes(0);
    endTime.setSeconds(0);

    // load and render editor into editor container
    var ddEditor_Schedule = new DragDropEditor();
    ddEditor_Schedule.load(0, 'scheduleDDEditorContainer', numCols, listTypes, scheduleEditorHeaders, 
                                '', scheduleEditorListLookupIds, startTime, endTime, 1800, 0, 880, 18, 55, 15, 5, null);
    ddEditor_Schedule.render();

    // remove loading msg
    $('pageContainer').removeClassName('fadedBG');
	$('loadingMsg').style.display = "none";
}

// function to go to previous week of schedules
function loadPrevWeek() {
	if (scheduleEditorIsModified > 0) {
	    $('unsavedChangesAlert').style.display = "block";
	    scheduleEditorPrevWeek = true;
	    return;
	}

    // hide hot keys
    //hideHotKeys();
    
    // show loading msg
    $('pageContainer').addClassName('fadedBG');
	$('loadingMsg').style.display = "block";

    // destroy active editor (this removes the editor from the editor array)
    activeEditor.destroy();
    
    // clear results box
    clearSearchResults();

    // load new editor params
    var numCols = 7;
    
    // get types of lists (in this case all slotted)
    var listTypes = [];
    for (var i=0; i<numCols; i++) {
        listTypes[i] = 0;
    }
    
    // update list lookup ids
    var prevDates = scheduleEditorListLookupIds;
    for (var i=0; i<7; i++) {
        var newDate = new Date(prevDates[i]);
        newDate.setDate(newDate.getDate() - 7);  // subtract 7 days
        var newMonth = parseInt((newDate.getMonth()+1),10).toPaddedString(2,10);
        var newDay = parseInt(newDate.getDate(),10).toPaddedString(2,10);
        var newYear = newDate.getFullYear();
        scheduleEditorListLookupIds[i] = newMonth + "/" + newDay + "/" + newYear;
        scheduleEditorHeaders[i] = scheduleEditorHeaders[i].substring(0,4);        
        scheduleEditorHeaders[i] += newMonth + "/" + newDay;
    }
    
    var startDateSplit = scheduleEditorListLookupIds[0].split("/");
    var startDate = startDateSplit[0] + "/" + startDateSplit[1] + "/" + startDateSplit[2].substr(2);
    var endDateSplit = scheduleEditorListLookupIds[6].split("/");
    var endDate = endDateSplit[0] + "/" + endDateSplit[1] + "/" + endDateSplit[2].substr(2);
    
    scheduleEditorHeader.innerHTML = "Schedules: Week of " + startDate + " - " + endDate;
    
    // get start and end times (in this case 24 hour day with 30 min increments)
    var startTime = new Date(0);
    startTime.setHours(0);
    startTime.setMinutes(0);
    startTime.setSeconds(0);
    var endTime = new Date(0);
    endTime.setHours(24);
    endTime.setMinutes(0);
    endTime.setSeconds(0);

    // load and render editor into editor container
    var ddEditor_Schedule = new DragDropEditor();
    ddEditor_Schedule.load(0, 'scheduleDDEditorContainer', numCols, listTypes, scheduleEditorHeaders, 
                                '', scheduleEditorListLookupIds, startTime, endTime, 1800, 0, 880, 18, 55, 15, 5, null);
    ddEditor_Schedule.render();

    // remove loading msg
    $('pageContainer').removeClassName('fadedBG');
	$('loadingMsg').style.display = "none";
}

// function to load a week of schedules into the currently viewed week
function copyWeekFrom() {
    var calendarRow = $('copyWeek_CalendarRow');
    var dateSelect = calendarRow.getElementsByTagName('select')[0];
    if (dateSelect.options.length != 7) {  // check that a week is selected
        $('copyWeekAlert').innerHTML = "&#149; Please select an entire week to copy."
        $('copyWeekAlert').style.display = "block";
    } else {
        // destroy active editor (this removes the editor from the editor array)
        activeEditor.destroy();
        
        // clear results box
        clearSearchResults();

        // load new editor params
        var numCols = 7;
        
        // get types of lists (in this case all slotted)
        var listTypes = [];
        for (var i=0; i<numCols; i++) {
            listTypes[i] = 0;
        }
        
        // update list lookup ids for load
        var tmpListLookupIds = [];
        for (var i=0, len=scheduleEditorListLookupIds.length; i<len; i++) {
            tmpListLookupIds[i] = scheduleEditorListLookupIds[i];
        }
        for (var i=0; i<7; i++) {
            var newDate = new Date(dateSelect.options[i].value);
            var newMonth = parseInt((newDate.getMonth()+1),10).toPaddedString(2,10);
            var newDay = parseInt(newDate.getDate(),10).toPaddedString(2,10);
            var newYear = parseInt(newDate.getYear(),10).toPaddedString(2,10);
            scheduleEditorListLookupIds[i] = newMonth + "/" + newDay + "/" + newYear;
        }
        
        // get start and end times (in this case 24 hour day with 30 min increments)
        var startTime = new Date(0);
        startTime.setHours(0);
        startTime.setMinutes(0);
        startTime.setSeconds(0);
        var endTime = new Date(0);
        endTime.setHours(24);
        endTime.setMinutes(0);
        endTime.setSeconds(0);

        // load and render editor into editor container
        var ddEditor_Schedule = new DragDropEditor();
        ddEditor_Schedule.load(0, 'scheduleDDEditorContainer', numCols, listTypes, scheduleEditorHeaders, 
                                    '', scheduleEditorListLookupIds, startTime, endTime, 1800, 0, 880, 18, 55, 15, 5, null);
        ddEditor_Schedule.render();
        
        // change list lookup ids on editor and lists back to match headers
        for (var i=0, len=tmpListLookupIds.length; i<len; i++) {
            scheduleEditorListLookupIds[i] = tmpListLookupIds[i];
            activeEditor.listLookupIds[i] = tmpListLookupIds[i];
            activeEditor.ddLists[i].listLookupId = tmpListLookupIds[i];
        }
//        activeEditor.listLookupIds = scheduleEditorListLookupIds;
//        for (var i=0, len=activeEditor.listLookupIds.length; i<len; i++) {
//            activeEditor.ddLists[i].listLookupId = activeEditor.listLookupIds[i];
//        }

        setPageModified(true);
        hideCopyWeekFrom();
    } 
}

function showCopyWeekFrom() {
    $('copyWeekFrom').style.display = "block";
    // cover page
    coverPageForAlert($('copyWeekFrom'));
}

function hideCopyWeekFrom() {
    uncoverPageForAlert();
    $('copyWeekAlert').style.display = "none";
    $('copyWeekFrom').style.display = "none";

}

function setPageModified (value) {
	//return;
	if (activeEditorPageId == 'scheduleEditor') {
	    //alert("schedule change");
	    if (value) {
	        scheduleEditorIsModified++;
	        //$('scheduleEditor_Save').removeAttribute('disabled');
	        if (scheduleEditorIsModified == 1) scheduleEditorHeader.innerHTML += "*";
	    } else {
	        scheduleEditorIsModified = 0;
	        //$('scheduleEditor_Save').setAttribute('disabled', 'disabled');
	       //scheduleEditorHeader.innerHTML = scheduleEditorHeader.innerHTML.substring(0,scheduleEditorHeader.innerHTML.length-1);
	       scheduleEditorHeader.innerHTML = scheduleEditorHeader.innerHTML.replace('*','');
	    }
	} else if (activeEditorPageId == 'packageEditor') {
	    //alert("package change");
	    if (value) {
	        packageEditorIsModified++;
	        //$('packageEditor_Save').removeAttribute('disabled');
	        if (packageEditorIsModified == 1) packageEditorHeader.innerHTML += "*";
	    } else {
	        packageEditorIsModified = 0;
	        //$('packageEditor_Save').setAttribute('disabled', 'disabled');
	        //packageEditorHeader.innerHTML = packageEditorHeader.innerHTML.substring(0,packageEditorHeader.innerHTML.length-1);
	        packageEditorHeader.innerHTML = packageEditorHeader.innerHTML.replace('*','');
	    }
	} else if (activeEditorPageId == 'eventEditor') {
	    //alert("event change");
	    if (value) {
	        eventEditorIsModified++;
	        //$('eventEditor_Save').removeAttribute('disabled');
	        if (eventEditorIsModified == 1) eventEditorHeader.innerHTML += "*";
	    } else {
	        eventEditorIsModified = 0;
	        //$('eventEditor_Save').setAttribute('disabled', 'disabled');
	        //eventEditorHeader.innerHTML = eventEditorHeader.innerHTML.substring(0,eventEditorHeader.innerHTML.length-1);
	        eventEditorHeader.innerHTML = eventEditorHeader.innerHTML.replace('*','');
	    }
	} else if (activeEditorPageId == 'comboEditor') {
	    if (value) {
	        comboEditorIsModified++;
	        //$('assetEditor_Save').removeAttribute('disabled');
	        if (comboEditorIsModified == 1) comboEditorHeader.innerHTML += "*";
	    } else {
	        comboEditorIsModified = 0;
	        //$('assetEditor_Save').setAttribute('disabled', 'disabled');
	        //comboEditorHeader.innerHTML = comboEditorHeader.innerHTML.substring(0,comboEditorHeader.innerHTML.length-1);
	        comboEditorHeader.innerHTML = comboEditorHeader.innerHTML.replace('*','');
	    }
	} else if (activeEditorPageId == 'assetEditor') {
	    //alert("asset change");
	    if (value) {
	        assetEditorIsModified++;
	        //$('assetEditor_Save').removeAttribute('disabled');
	        if (assetEditorIsModified == 1) assetEditorHeader.innerHTML += "*";
	    } else {
	        assetEditorIsModified = 0;
	        //$('assetEditor_Save').setAttribute('disabled', 'disabled');
	        //assetEditorHeader.innerHTML = assetEditorHeader.innerHTML.substring(0,assetEditorHeader.innerHTML.length-1);
	        assetEditorHeader.innerHTML = assetEditorHeader.innerHTML.replace('*','');
	    }
	} else if (activeEditorPageId == 'multiPackage') {
	    //alert("package change");
	    if (value) {
	        multiPackageIsModified++;
	        //$('packageEditor_Save').removeAttribute('disabled');
	        if (multiPackageIsModified == 1) multiPackageHeader.innerHTML += "*";
	    } else {
	        multiPackageIsModified = 0;
	        //$('packageEditor_Save').setAttribute('disabled', 'disabled');
	        //packageEditorHeader.innerHTML = packageEditorHeader.innerHTML.substring(0,packageEditorHeader.innerHTML.length-1);
	        multiPackageHeader.innerHTML = multiPackageHeader.innerHTML.replace('*','');
	    }
	}
}

// for editor pages
function checkReturn(element, href) {

    activeReturnHref = href;
    
    var btnValue = element.value;
    var isCancel = btnValue.match(/cancel/i);

	if (activeEditorPageId == 'scheduleEditor') {
	    activeDrillLevel = 0;
	    if (scheduleEditorIsModified > 0 && !isCancel) {
	        $('unsavedChangesAlert').style.display = "block";
	    } else {
	        saveContinue(false);
	    }
	} else if (activeEditorPageId == 'packageEditor') {
	    activeDrillLevel = 1;
	    if (packageEditorIsModified > 0 && !isCancel){
	        $('unsavedChangesAlert').style.display = "block";
	    } else {
	        saveContinue(false);
	    }
	} else if (activeEditorPageId == 'eventEditor') {
	    activeDrillLevel = 2;
	    if (eventEditorIsModified > 0 && !isCancel ) {
	        $('unsavedChangesAlert').style.display = "block";
	    } else {
	        saveContinue(false);
	    }
	} else if (activeEditorPageId == 'comboEditor') {
	    activeDrillLevel = 3;
	    if (comboEditorIsModified > 0 && !isCancel) {
	        $('unsavedChangesAlert').style.display = "block";
	    } else {
	        saveContinue(false);
	    }
	} else if (activeEditorPageId == 'assetEditor') {
	    //activeDrillLevel = editors.length-1;
	    if (assetEditorReturnChoice == "Events") {
	        activeDrillLevel = 3;
	    } else {
	        activeDrillLevel = 4;
	    }
	    if (assetEditorIsModified > 0 && !isCancel) {
	        $('unsavedChangesAlert').style.display = "block";
	    } else {
	        saveContinue(false);
	    }
	} else if (activeEditorPageId == 'multiPackage') {
	    if (multiPackageIsModified > 0 && !isCancel) {
	        $('unsavedChangesAlert').style.display = "block";
	    } else {
	        saveContinue(false);
	    }
	} else {
	    location.href = href;
	}
}

function checkReturnTopNav (href) {

    activeReturnHref = href;
    if (activeEditorPageId == 'assetEditor') {
        if ( (comboEditorIsModified > 0) || (eventEditorIsModified > 0) || (packageEditorIsModified > 0) || (scheduleEditorIsModified > 0) ) {
            $('unsavedChangesTopNavAlert').style.display = "block";
        } else if (assetEditorIsModified > 0) {
            $('unsavedChangesAlert').style.display = "block";
        } else {
            saveContinueTopNav();
        }
    } else if (activeEditorPageId == 'comboEditor') {
        if ( (eventEditorIsModified > 0) || (packageEditorIsModified > 0) || (scheduleEditorIsModified > 0) ) {
            $('unsavedChangesTopNavAlert').style.display = "block";
        } else if (comboEditorIsModified > 0) {
            $('unsavedChangesAlert').style.display = "block";    
        } else {
            saveContinueTopNav();
        }    
    } else if (activeEditorPageId == 'eventEditor') {
        if ( (packageEditorIsModified > 0) || (scheduleEditorIsModified > 0) ) {
            $('unsavedChangesTopNavAlert').style.display = "block";
        } else if (eventEditorIsModified > 0) {
            $('unsavedChangesAlert').style.display = "block";  
        } else {
            saveContinueTopNav();
        }
    } else if (activeEditorPageId == 'packageEditor') {
        if ( (scheduleEditorIsModified > 0) ) {
            $('unsavedChangesTopNavAlert').style.display = "block";
        } else if (packageEditorIsModified > 0) {
            $('unsavedChangesAlert').style.display = "block";  
        } else {
            saveContinueTopNav();
        }
    } else if (activeEditorPageId == 'scheduleEditor') {
        if (scheduleEditorIsModified > 0) {
            $('unsavedChangesAlert').style.display = "block"; 
        } else {
            saveContinueTopNav();
        }
    } else if (activeEditorPageId == 'multiPackage') {
        if (multiPackageIsModified > 0) {
            $('unsavedChangesAlert').style.display = "block"; 
        } else {
            saveContinueTopNav();
        }
    } else if (activeEditorPageId == 'liveControl') {
        saveContinueTopNav();
    } else {
        location.href = activeReturnHref;
        activeReturnHref = "";
    }
    
//    if ( (assetEditorIsModified > 0) || (comboEditorIsModified > 0) || (eventEditorIsModified > 0) || (packageEditorIsModified > 0) || (scheduleEditorIsModified > 0) ) {
//        $('unsavedChangesTopNavAlert').style.display = "block";
//    } else {
//        location.href = activeReturnHref;
//        activeReturnHref = "";
//    }
}


function saveContinue (value) {
    if ($('unsavedChangesAlert')) $('unsavedChangesAlert').style.display = "none";
    if ($('unsavedChangesTopNavAlert')) $('unsavedChangesTopNavAlert').style.display = "none";
    if (value) { // save
        // do nothing - this is currently not used 
    } else {  // continue without save
        if (activeEditor.systemLevel != 0) {
            // close the open object
            objForEditClose();
        }
        if (activeReturnHref != "") {
            activeEditor.destroy();  // when you leave the editor page this makes sure to clean up
            location.href = activeReturnHref;
            activeReturnHref = "";
        } else if (activeEditor.systemLevel == 0) {
            scheduleEditorIsModified = 0;
            if (scheduleEditorNextWeek) {
                scheduleEditorNextWeek = false;
                loadNextWeek();
            }
            if (scheduleEditorPrevWeek) {
                scheduleEditorPrevWeek = false;
                loadPrevWeek();
            }
        } else {
            if (activeEditorPageId == 'assetEditor') assetEditorIsModified = 0;
            if (activeEditorPageId == 'comboEditor') comboEditorIsModified = 0;
            if (activeEditorPageId == 'eventEditor') eventEditorIsModified = 0;
            if (activeEditorPageId == 'packageEditor') packageEditorIsModified = 0;
            if (createNewFlag == true) {
                createNewFlag == false;
                createNew();
            } else {
                drillUp(activeDrillLevel-1);
            }
        }
    }
}

function saveContinueTopNav () {
    if ($('unsavedChangesAlert')) $('unsavedChangesAlert').style.display = "none";
    if ($('unsavedChangesTopNavAlert')) $('unsavedChangesTopNavAlert').style.display = "none";
    // close all open objects
    var closeAllRequest = new XMLHttpRequest();
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_ObjForEditCloseAll\" />";
    var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
    xmlStr += "<ROOT>";
    xmlStr += sProc;
    xmlStr += "</ROOT>";
    var url = "AjaxPost.aspx";
    closeAllRequest = new XMLHttpRequest();
    closeAllRequest.open('POST', url, false);
    closeAllRequest.setRequestHeader("Content-Type", "text/xml");
    closeAllRequest.send(xmlStr);
    //callAjaxPost(closeAllRequest, sProc, null);    
    
    if (activeReturnHref != "") {
        location.href = activeReturnHref;
        activeReturnHref = "";
    }
}

// ajax state change handler
function processSaveEditorStateChange () {
	if (saveEditorRequest.readyState == 4) {
		if (saveEditorRequest.status == 200) {
		    postSaveUpdate(saveEditorRequest.responseText);
		}
	} 
}

// post save update to update 
function postSaveUpdate(returnValue) {
    if (returnValue > 0) {
        if (activeEditor.systemLevel == 4) {  // update asset
            // get asset id and assign the return value
            var assetId = parseInt(returnValue,10);
            var asset = assetRequest.responseXML.getElementsByTagName('ASSET')[0];
            asset.removeAttribute('ID');
            asset.setAttribute('ID', assetId);
            
            // call sproc to show object open
            objForEditOpen(assetId,4); 
            
            // display save message
            msgNode = $('assetEditor_Messages');
            msgNode.style.color = "Green";
            msgNode.style.fontWeight = "Bold";
            msgNode.innerHTML = "Successful Save" + " (id = " + saveEditorRequest.responseText + ")";
            msgNode.style.display = "block";
            
             // set header
	        if (assetEditorReturnChoice == "Events") {
                assetEditorHeader.innerHTML = eventEditorDrillHeader + 'Asset: ' + $('assetEditor_Name').value.strip();
            } else {
                assetEditorHeader.innerHTML = comboEditorDrillHeader + 'Asset: ' + $('assetEditor_Name').value.strip();
            }           
            
            // enabled save copy button
            $('assetEditor_SaveCopy').removeAttribute('disabled');
            
            // update id
            $('assetEditor_Id').value = assetId;
            
            // lock duration and channel
            $('assetEditor_Duration').setAttribute('disabled','disabled');
            $('assetEditor_Channel').setAttribute('disabled','disabled');
            
            // update all instances of this object in the parent editor if we drilled down
            if (editors.length > 1) {
                var parentEditor = editors[editors.length-2];
                var parentPecas = parentEditor.draggablePecas;
                for (i=0, len=parentPecas.length; i<len; i++) {
                    if (parentPecas[i].dbId == assetId) {
                        // update object properties
                        parentPecas[i].name = $('assetEditor_Name').value.strip();
                        var colorRGB = $('assetEditor_Color').style.backgroundColor;
                        colorRGB = colorRGB.substring(colorRGB.indexOf('(')+1, colorRGB.indexOf(')'));
                        var rgbSplit = colorRGB.split(',');
                        var color = rgb2hex(rgbSplit[0], rgbSplit[1], rgbSplit[2]);
                        parentPecas[i].thisColor = color;
                        parentPecas[i].fontColor = parentPecas[i].assignFontColor();
                        // update rendered elements as well
                        var parentContainer = $(parentEditor.containerId);
                        var selector = "";
                        if (assetEditorReturnChoice == "Events") {
                            selector = "li#" + parentPecas[i].tagId;
                        } else {
                            selector = "div#" + parentPecas[i].tagId;
                        }
                        var parentEl = parentContainer.getElementsBySelector(selector)[0];
                        if (parentEl) {
                            parentEl.innerHTML = $('assetEditor_Name').value.strip();
                            parentEl.style.backgroundColor = "#" + color;
                            parentEl.style.color = parentPecas[i].fontColor;
                        }
                    }
                }
            }
        } else if (activeEditor.systemLevel == 3) {  // save combo
            // get combo id and assign the return value
            var comboId = parseInt(returnValue,10);
            var combo = comboRequest.responseXML.getElementsByTagName('ASSET')[0];
            combo.removeAttribute('ID');
            combo.setAttribute('ID', comboId);
           
            // call sproc to show object open
            objForEditOpen(comboId,3); 
            
            // display save message
            msgNode = $('comboEditor_Messages');
            msgNode.style.color = "Green";
            msgNode.style.fontWeight = "Bold";
            msgNode.innerHTML = "Successful Save" + " (id = " + saveEditorRequest.responseText + ")";
            msgNode.style.display = "block";
            
            // update header
            comboEditorHeader.innerHTML = eventEditorDrillHeader + 'Combo: ' + $('comboEditor_Name').value.strip();
            
            // enabled save copy button
            $('comboEditor_SaveCopy').removeAttribute('disabled');
            
            // update id
            $('comboEditor_Id').value = comboId;
            
            // lock duration and channel
            $('comboEditor_Duration').setAttribute('disabled','disabled');
            $('comboEditor_Channel').setAttribute('disabled','disabled');
            
            // lock default combo box if checked
            if ($('comboEditor_DefaultCombo').checked) {
                $('comboEditor_DefaultCombo').setAttribute('disabled','disabled');
            }
            
            // update all instances of this object in the parent editor if we drilled down
            if (editors.length > 1) {
                var parentEditor = editors[editors.length-2];
                var parentPecas = parentEditor.draggablePecas;
                for (i=0, len=parentPecas.length; i<len; i++) {
                    if (parentPecas[i].dbId == comboId) {
                        // update object properties
                        parentPecas[i].name = $('comboEditor_Name').value.strip();
                        var colorRGB = $('comboEditor_Color').style.backgroundColor;
                        colorRGB = colorRGB.substring(colorRGB.indexOf('(')+1, colorRGB.indexOf(')'));
                        var rgbSplit = colorRGB.split(',');
                        var color = rgb2hex(rgbSplit[0], rgbSplit[1], rgbSplit[2]);
                        parentPecas[i].thisColor = color;
                        parentPecas[i].fontColor = parentPecas[i].assignFontColor();
                        // update rendered elements as well
                        var parentContainer = $(parentEditor.containerId);
                        var selector = "li#" + parentPecas[i].tagId;
                        var parentEl = parentContainer.getElementsBySelector(selector)[0];
                        if (parentEl) {
                            parentEl.innerHTML = $('comboEditor_Name').value.strip();
                            parentEl.style.backgroundColor = "#" + color;
                            parentEl.style.color = parentPecas[i].fontColor;
                        }
                    }
                }
            }
            
        }  else if (activeEditor.systemLevel == 2) {  // save event
            // get event id and assign the return value
            var eventId = parseInt(returnValue,10);
            var eventobj = eventRequest.responseXML.getElementsByTagName('EVENT')[0];
            eventobj.removeAttribute('ID');
            eventobj.setAttribute('ID', eventId);
            
            // call sproc to show object open
            objForEditOpen(eventId,2); 
            
            // display save message
            msgNode = $('eventEditor_Messages');
            msgNode.style.color = "Green";
            msgNode.style.fontWeight = "Bold";
            msgNode.innerHTML = "Successful Save" + " (id = " + saveEditorRequest.responseText + ")";
            msgNode.style.display = "block";
            
            // update header
            eventEditorHeader.innerHTML = packageEditorDrillHeader + 'Event: ' + $('eventEditor_Name').value.strip();
           
           // enable save copy button
            $('eventEditor_SaveCopy').removeAttribute('disabled');
           
           // update id
            $('eventEditor_Id').value = eventId;
           
            // lock duration
            $('eventEditor_Duration').setAttribute('disabled','disabled');
            // reset duration updated to false
            //eventEditorDurationUpdated = false;
            
            // update editor for possible new duration
            var duration = $('eventEditor_Duration').value.strip();
            var editorLastDur = activeEditor.timeStrs.last();
            
            if (duration < editorLastDur) {
                activeEditor.shortenDuration(duration);
            } else if (duration > editorLastDur) {
                activeEditor.lengthenDuration(duration);
            }
            
            // update all instances of this object in the parent editor if we drilled down
            if (editors.length > 1) {
                var parentEditor = editors[editors.length-2];
                var parentPecas = parentEditor.draggablePecas;
                for (i=0, len=parentPecas.length; i<len; i++) {
                    if (parentPecas[i].dbId == eventId) {
                        // update object properties
                        parentPecas[i].name = $('eventEditor_Name').value.strip();
                        var colorRGB = $('eventEditor_Color').style.backgroundColor;
                        colorRGB = colorRGB.substring(colorRGB.indexOf('(')+1, colorRGB.indexOf(')'));
                        var rgbSplit = colorRGB.split(',');
                        var color = rgb2hex(rgbSplit[0], rgbSplit[1], rgbSplit[2]);
                        parentPecas[i].thisColor = color;
                        parentPecas[i].fontColor = parentPecas[i].assignFontColor();
                        // update rendered elements as well
                        var parentContainer = $(parentEditor.containerId);
                        var selector = "li#" + parentPecas[i].tagId;
                        var parentEl = parentContainer.getElementsBySelector(selector)[0];
                        if (parentEl) {
                            parentEl.style.backgroundColor = "#" + color;
                            parentEl.style.color = parentPecas[i].fontColor;
                            parentEl.innerHTML = $('eventEditor_Name').value.strip();

                        }
                    }
                }
            }
            
        } else if (activeEditor.systemLevel == 1) {  // save package
            // get package id and assign the return value
            var packageId = parseInt(returnValue,10);
            
            // close previous package
            objForEditClose();
            
            var packageobj = packageRequest.responseXML.getElementsByTagName('PACKAGE')[0];
            packageobj.removeAttribute('ID');
            packageobj.setAttribute('ID', packageId);
            
            // update color
            var colorRGB = $('packageEditor_Color').style.backgroundColor;
            colorRGB = colorRGB.substring(colorRGB.indexOf('(')+1, colorRGB.indexOf(')'));
            var rgbSplit = colorRGB.split(',');
            var color = rgb2hex(rgbSplit[0], rgbSplit[1], rgbSplit[2]);
            packageobj.removeAttribute('ThisColor');
            packageobj.setAttribute('ThisColor', color);

            
            // call sproc to show object open
            objForEditOpen(packageId,1); 
            
            // display save message
            msgNode = $('packageEditor_Messages');
            msgNode.style.color = "Green";
            msgNode.style.fontWeight = "Bold";
            msgNode.innerHTML = "Successful Save" + " (id = " + saveEditorRequest.responseText + ")";
            msgNode.style.display = "block";
            
            // update header
            packageEditorHeader.innerHTML = scheduleEditorDrillHeader + 'Package: ' + $('packageEditor_Name').value.strip();
            
            // enabled save copy button
            $('packageEditor_SaveCopy').removeAttribute('disabled');
            
            // update id
            $('packageEditor_Id').value = packageId;
            
            // lock duration
            $('packageEditor_Duration').setAttribute('disabled','disabled');
            
            // update all instances of this object in the parent editor if we drilled down
            if (editors.length > 1) {
                var parentEditor = editors[editors.length-2];
                var parentPecas = parentEditor.draggablePecas;
                if (packageEditorPackageDate != '') {  // process a save package instance
                    var inputs = $('savePackageInstance').getElementsByTagName('input');
                    if (inputs[0].checked) { // only this instance
                        // create new peca using current xml
                        var newInstancePeca = loadPackageFromXML(packageobj);
                        // replace auto generated tag_id with one from parent editor and change name to new name
                        newInstancePeca.tagId = "peca_" + parentEditor.draggablePecaIndex++;                  
                        newInstancePeca.name = $('packageEditor_Name').value.strip();
                        var newInstancePecaEl = newInstancePeca.render();
                        var parentNode = packageEditorPecaEl.parentNode;
                        removeDragObservers(packageEditorPecaEl);
                        packageEditorPecaEl.remove();
                        
                        newInstancePecaEl.style.width = parentEditor.cellWidth + "px";
			            newInstancePecaEl.style.padding = "0 " + parentEditor.cellPadding + "px";
			            newInstancePecaEl.style.height = parentEditor.cellHeight + "px";
                        parentNode.appendChild(newInstancePecaEl);
                        //addDrag(newInstancePecaEl);  this happens when activated
                        parentPecas.push(newInstancePeca);
                        parentEditor.validatePackage(newInstancePecaEl, parentNode);
                        packageEditorPecaEl = newInstancePecaEl;
                    } else {  // instances in the range
                        var dateFrom = ConvertToXMLDate($('savePackageDateFrom').value.strip());
                        var dateTo = ConvertToXMLDate($('savePackageDateTo').value.strip());
                        // process parent editor's schedules one by one
                        var parentLists = parentEditor.ddLists;
                        var oldPeca = parentEditor.getPeca(packageEditorPecaEl);
                        var oldId = oldPeca.dbId;
                        for (var i=0, len=parentLists.length; i<len; i++) {
                            var listDate = ConvertToXMLDate(parentLists[i].listLookupId);
                            if ( (listDate >= dateFrom) && (listDate <= dateTo) ) { // update instances in this list
                                var listEls = $(parentLists[i].tagId).immediateDescendants();
                                for (var j=0, jlen=listEls.length; j<jlen; j++) {
                                    if (listEls[j].firstDescendant()) { // if slot is occupied
                                        var checkPeca = parentEditor.getPeca(listEls[j].firstDescendant());
                                        if (checkPeca.dbId == oldId) {  // if this package matches the new instance
                                            // create new peca using current xml
                                            var newInstancePeca = loadPackageFromXML(packageobj);
                                            // replace auto generated tag_id with one from parent editor and change name to new name
                                            newInstancePeca.tagId = "peca_" + parentEditor.draggablePecaIndex++;                  
                                            newInstancePeca.name = $('packageEditor_Name').value.strip();
                                            var newInstancePecaEl = newInstancePeca.render();
                                            var parentNode = listEls[j];
                                            removeDragObservers(listEls[j].firstDescendant());
                                            listEls[j].firstDescendant().remove();
                                            
                                            newInstancePecaEl.style.width = parentEditor.cellWidth + "px";
			                                newInstancePecaEl.style.padding = "0 " + parentEditor.cellPadding + "px";
			                                newInstancePecaEl.style.height = parentEditor.cellHeight + "px";
                                            listEls[j].appendChild(newInstancePecaEl);
                                            //addDrag(newInstancePecaEl);  this happens when activated
                                            parentPecas.push(newInstancePeca);
                                            parentEditor.validatePackage(newInstancePecaEl, listEls[j]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {  // process a regular save
                    if (editors.length > 1) {
                        var parentEditor = editors[editors.length-2];
                        var parentPecas = parentEditor.draggablePecas;
                        for (i=0, len=parentPecas.length; i<len; i++) {
                            if (parentPecas[i].dbId == packageId) {
                                // update object properties
                                parentPecas[i].name = $('packageEditor_Name').value.strip();
                                var colorRGB = $('packageEditor_Color').style.backgroundColor;
                                colorRGB = colorRGB.substring(colorRGB.indexOf('(')+1, colorRGB.indexOf(')'));
                                var rgbSplit = colorRGB.split(',');
                                var color = rgb2hex(rgbSplit[0], rgbSplit[1], rgbSplit[2]);
                                parentPecas[i].thisColor = color;
                                parentPecas[i].fontColor = parentPecas[i].assignFontColor();
                                // update rendered elements as well
                                var parentContainer = $(parentEditor.containerId);
                                var selector = "div#" + parentPecas[i].tagId;
                                var parentEl = parentContainer.getElementsBySelector(selector)[0];
                                //var parentEl = $(parentPecas[i].tagId);
                                if (parentEl) {
                                    parentEl.innerHTML = $('packageEditor_Name').value.strip();
                                    parentEl.style.backgroundColor = "#" + color;
                                    parentEl.style.color = parentPecas[i].fontColor;
                                }
                            }
                        }       
                    }  
                }  
            }        
        } else if (activeEditor.systemLevel == 0) {  // save schedules
            // post schedule change
            
        }
    setPageModified(false);
    }
}

// function to save new object
var saveEditorRequest = new XMLHttpRequest();	
function saveEditorObject() {
    if (validateForm()) {
        var sessionIdBLStr = "SessionID=\"" + sessionId + "\" ";
        if (activeEditor.systemLevel == 4) {  // save asset
            // get asset id
            var asset = assetRequest.responseXML.getElementsByTagName('ASSET')[0];
            var id = asset.getAttribute('ID');
            var idBLStr = (id != '') ? ("ID=\"" + id + "\" ") : ("ID=\"-1\" ");
            
            // create xml
            var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
            xmlStr += "<ROOT>";
            
            // assign stored procedure
            if (id == -1) {
                xmlStr += "<STOREDPROCEDURE Name=\"sproc_WEB_InsertFromBLAsset\" />";
                asset.removeAttribute('ThisEnabled');
                asset.setAttribute('ThisEnabled', 1);
                asset.removeAttribute('EnabledNN');
                asset.setAttribute('EnabledNN', 1); 
            } else {
                xmlStr += "<STOREDPROCEDURE Name=\"sproc_WEB_UpdateFromBLAsset\" />";
            }

            // get enabled status and pass-through (both fields required)
            var thisEnabledValue = (asset.getAttribute('ThisEnabled') == 1) ? "true" : "false"; 
            var enabledNNValue = (asset.getAttribute('EnabledNN') == 1) ? "true" : "false"; 
            var thisEnabled = "ThisEnabled=\"" + thisEnabledValue + "\" ";
            var enabledNN = "EnabledNN=\"" + enabledNNValue + "\" ";

            // get properties
            //var id = -1;  // id of -1 for new asset
            var name = ($('assetEditor_Name').value.strip() != '') ? ("Name=\"" + escapeForXML($('assetEditor_Name').value.strip()) + "\" ") : "";
            //name.replace(/&/g,"&amp;");
            //var channel = ($('assetEditor_Channel') != 0) ? ("ChannelsNN=\"" + "," + $('assetEditor_Channel').value + "," + "\" ") : "";
            var channel = "ChannelsNN=\"" + "," + $('assetEditor_Channel').options[$('assetEditor_Channel').selectedIndex].value + "," + "\" "
            var thisStartDate = ($('assetEditor_AirDateFrom').value.strip() != '') ? ("ThisStartDate=\"" + ConvertToXMLDate($('assetEditor_AirDateFrom').value.strip()) + "\" ") : "";
            var thisEndDate = ($('assetEditor_AirDateTo').value.strip() != '') ? ("ThisEndDate=\"" + ConvertToXMLDate($('assetEditor_AirDateTo').value.strip()) + "\" ") : "";
            var duration = ($('assetEditor_Duration').value.strip() != '') ? ("Duration=\"" + ConvertToXMLDate($('assetEditor_Duration').value.strip()) + "\" ") : "";
            var colorRGB = $('assetEditor_Color').style.backgroundColor;
            colorRGB = colorRGB.substring(colorRGB.indexOf('(')+1, colorRGB.indexOf(')'));
            var rgbSplit = colorRGB.split(',');
            var color = rgb2hex(rgbSplit[0], rgbSplit[1], rgbSplit[2]);
            color = "ThisColor=\"" + color + "\" ";
            // add video source to cue string start if exists
            var cueStringStartBase = "";
            var sourceSelect = $('assetEditor_VideoSource');
            if (sourceSelect.selectedIndex > 0) {
                cueStringStartBase = sourceSelect.options[sourceSelect.selectedIndex].value + ",";
            }
            
            var cueStringStart = "";
            if ($('assetEditor_CueStringStart').value.strip() != '') {
                cueStringStart = "CueStringStart=\"" + cueStringStartBase + escapeForXML($('assetEditor_CueStringStart').value.strip()) + "\" ";
            } else if (cueStringStartBase.length > 0) {
                cueStringStart = "CueStringStart=\"" + escapeForXML(cueStringStartBase) + "\" ";
            }
            
            cueStringEnd = ($('assetEditor_CueStringEnd').value.strip() != '') ? ("CueStringEnd=\"" + escapeForXML($('assetEditor_CueStringEnd').value.strip()) + "\" ") : "";

            var dayPart = "ThisDayPart=\"" + getDPR() + "\" ";
            
            // set ingestednn and onplayersnn according to video source
            var channelSelect = $('assetEditor_Channel');
            var ingestedNNStr = "IngestedNN=\"false\" ";
            var onPlayersNNStr = "OnPlayersNN=\"false\" ";
            if (channelSelect.selectedIndex != 0) {
                var videoSourceSelect = $('assetEditor_VideoSource');
                var videoSourceValue = videoSourceSelect.options[videoSourceSelect.selectedIndex].value;
                if ( (channelSelect.options[channelSelect.selectedIndex].value == 1) ) { // Mitsubishi
                    var mitsuMatchValues = /10|11/;
                    if (videoSourceValue.search(mitsuMatchValues) < 0) {
                        ingestedNNStr = "IngestedNN=\"true\" ";
                        onPlayersNNStr = "OnPlayersNN=\"true\" ";
                    }
                } else if (channelSelect.options[channelSelect.selectedIndex].value == 2) { // Ribbons
                    var ribbonsMatchValues = /30|33|34|47|54|61/;
                    if (videoSourceValue.search(ribbonsMatchValues) < 0) {
                        ingestedNNStr = "IngestedNN=\"true\" ";
                        onPlayersNNStr = "OnPlayersNN=\"true\" ";
                    }
               } else if (channelSelect.options[channelSelect.selectedIndex].value == 3) { // Ticker
                    var tickersMatchValues = /70/;
                    if (videoSourceValue.search(tickersMatchValues) < 0) {
                        ingestedNNStr = "IngestedNN=\"true\" ";
                        onPlayersNNStr = "OnPlayersNN=\"true\" ";
                    }
               }

            }
            
            //xmlStr += "<BL_ASSET BLID=\"\" IsCombo=\"false\" ThisEnabled=\"true\" EnabledNN=\"true\" ";  WGO 2007-12-18: Adding enabled options to string below
            xmlStr += "<BL_ASSET BLID=\"\" IsCombo=\"false\" ";
            xmlStr += thisEnabled + enabledNN + name + channel + thisStartDate + thisEndDate + duration + cueStringStart + cueStringEnd + color + ingestedNNStr + onPlayersNNStr + sessionIdBLStr + idBLStr + dayPart;
            xmlStr += "/>";               
                        
            // get metadata values
            var metaDataFields = $('assetEditorMetaData').getElementsByClassName('metadata');
            xmlStr += writeMDXML(metaDataFields, id);
            
            // get tasks
            var tasks = assetRequest.responseXML.getElementsByTagName('TASK');
            for (var i=0, len=tasks.length; i<len; i++) {
                tasks[i].removeAttribute('ID');
                var blTaskStr = tasks[i].xml.toString();
                blTaskStr = blTaskStr.replace('TASK', 'BL_TASK BLID=\"\" ' + sessionIdBLStr);
                xmlStr += blTaskStr;
            }
            
            // create bl_mediainstance rows
            
            //var channelSelect = $('assetEditor_Channel');
            if (channelSelect.selectedIndex != 0) {
                var assetIdBLStr = (id != '') ? ("AssetID=\"" + id + "\" ") : ("AssetID=\"-1\" ");
                var fileBaseStr = "<BL_MEDIAINSTANCE BLID=\"\" ID=\"-1\" Enabled=\"true\" " +
                                    "TransferPriority=\"10\" FilesPresentNN=\"0\" FilesPresentBackupNN=\"0\" ";
                var videoSourceSelect = $('assetEditor_VideoSource');
                var videoSourceValue = videoSourceSelect.options[videoSourceSelect.selectedIndex].value;
                if ( (channelSelect.options[channelSelect.selectedIndex].value == 1) ) { // Mitsubishi
                    var mediaId1 = $('assetEditor_FileId1');
                    var media1 = "";
                    var fullyPresentStr1 = "FullyPresentNN=\"false\" ";
                    var fullyPresentBackupStr1 = "FullyPresentBackupNN=\"false\" ";
                    if (mediaId1) {
                        if (mediaId1.innerHTML.length > 0) {
                            media1 = "MediaID=\"" + escapeForXML(mediaId1.innerHTML) + "\" ";
                        }
                    }
                    var mitsuMatchValues = /10|11/;
                    if (videoSourceValue.search(mitsuMatchValues) < 0) {
                        fullyPresentStr1 = "FullyPresentNN=\"true\" ";
                        fullyPresentBackupStr1 = "FullyPresentBackupNN=\"true\" ";
                    }
                    var player = "PlayerID=\"1\" ";
                    
                    xmlStr += fileBaseStr + media1 + player + fullyPresentStr1 + fullyPresentBackupStr1 + sessionIdBLStr + assetIdBLStr + "/>";
                } else if (channelSelect.options[channelSelect.selectedIndex].value == 2) { // Ribbons
                    var mediaId1 = $('assetEditor_FileId1');
                    var media1 = "";
                    var fullyPresentStr1 = "FullyPresentNN=\"false\" ";
                    var fullyPresentBackupStr1 = "FullyPresentBackupNN=\"false\" ";
                    if (mediaId1) {
                        if (mediaId1.innerHTML.length > 0) {
                            media1 = "MediaID=\"" + escapeForXML(mediaId1.innerHTML) + "\" ";
                        }
                    }
                    var ribbonsLeftMatchValues = /30|33|34|47|54|61/;
                    if (videoSourceValue.search(ribbonsLeftMatchValues) < 0) {
                        fullyPresentStr1 = "FullyPresentNN=\"true\" ";
                        fullyPresentBackupStr1 = "FullyPresentBackupNN=\"true\" ";
                    }
                    var mediaId2 = $('assetEditor_FileId2');
                    var media2 = "";
                    var fullyPresentStr2 = "FullyPresentNN=\"false\" ";
                    var fullyPresentBackupStr2 = "FullyPresentBackupNN=\"false\" ";
                    if (mediaId2) {
                        if (mediaId2.innerHTML.length > 0) {
                            media2 = "MediaID=\"" + escapeForXML(mediaId2.innerHTML) + "\" ";
                        }
                    }
                    var ribbonsRightMatchValues = /30/;
                    if (videoSourceValue.search(ribbonsRightMatchValues) < 0) {
                        fullyPresentStr2 = "FullyPresentNN=\"true\" ";
                        fullyPresentBackupStr2 = "FullyPresentBackupNN=\"true\" ";
                    }
                    var player1 = "PlayerID=\"2\" ";
                    var player2 = "PlayerID=\"3\" ";
                    var fileBaseStr1 = fileBaseStr + media1 + player1 + fullyPresentStr1 + fullyPresentBackupStr1 + sessionIdBLStr + assetIdBLStr + "/>";
                    var fileBaseStr2 = fileBaseStr + media2 + player2 + fullyPresentStr2 + fullyPresentBackupStr2 + sessionIdBLStr + assetIdBLStr + "/>";
                    xmlStr += fileBaseStr1 + fileBaseStr2;
                }  else if (channelSelect.options[channelSelect.selectedIndex].value == 3) { // Ticker
                    var mediaId1 = $('assetEditor_FileId1');
                    var media1 = "";
                    var fullyPresentStr1 = "FullyPresentNN=\"false\" ";
                    var fullyPresentBackupStr1 = "FullyPresentBackupNN=\"false\" ";
                    if (mediaId1) {
                        if (mediaId1.innerHTML.length > 0) {
                            media1 = "MediaID=\"" + escapeForXML(mediaId1.innerHTML) + "\" ";
                        }
                    }
                    var tickersMatchValues = /70/;
                    if (videoSourceValue.search(tickersMatchValues) < 0) {
                        fullyPresentStr1 = "FullyPresentNN=\"true\" ";
                        fullyPresentBackupStr1 = "FullyPresentBackupNN=\"true\" ";
                    }
                    var player1 = "PlayerID=\"4\" ";
                    xmlStr += fileBaseStr + media1 + player1 + fullyPresentStr1 + fullyPresentBackupStr1  + sessionIdBLStr + assetIdBLStr + "/>";
                }
            }

            xmlStr += "</ROOT>";
            url = "AjaxPost.aspx";
            saveEditorRequest.open('POST', url, true);
            saveEditorRequest.setRequestHeader("Content-Type", "text/xml");
            saveEditorRequest.send(xmlStr);	
            saveEditorRequest.onreadystatechange = processSaveEditorStateChange;	
            
        } else if (activeEditor.systemLevel == 3) {  // save combo
            // get combo id
            var combo = comboRequest.responseXML.getElementsByTagName('ASSET')[0];
            var id = combo.getAttribute('ID');
            var idBLStr = (id != '') ? ("ID=\"" + id + "\" ") : ("ID=\"-1\" ");
            
            // create xml
            var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
            xmlStr += "<ROOT>";
     
            // assign stored procedure
            if (id == -1) {
                xmlStr += "<STOREDPROCEDURE Name=\"sproc_WEB_InsertFromBLCombo\" />";
                combo.removeAttribute('ThisEnabled');
                combo.setAttribute('ThisEnabled', 1);
                combo.removeAttribute('EnabledNN');
                combo.setAttribute('EnabledNN', 1);                
            } else {
                xmlStr += "<STOREDPROCEDURE Name=\"sproc_WEB_UpdateFromBLCombo\" />";
            }
     
            // get enabled status and pass-through (both fields required)
            var thisEnabledValue = (combo.getAttribute('ThisEnabled') == 1) ? "true" : "false"; 
            var enabledNNValue = (combo.getAttribute('EnabledNN') == 1) ? "true" : "false"; 
            var thisEnabled = "ThisEnabled=\"" + thisEnabledValue + "\" ";
            var enabledNN = "EnabledNN=\"" + enabledNNValue + "\" ";    
     
            // get properties
            //var id = -1;  // id of -1 for new combo
            var name = ($('comboEditor_Name').value.strip() != '') ? ("Name=\"" + escapeForXML($('comboEditor_Name').value.strip()) + "\" ") : "";
            //var channel = ($('comboEditor_Channel') != 0) ? ("ChannelsNN=\"" + "," + $('comboEditor_Channel').value + "," + "\" ") : "";
            var channel = "ChannelsNN=\"" + "," + $('comboEditor_Channel').options[$('comboEditor_Channel').selectedIndex].value + "," + "\" ";
            var thisStartDate = ($('comboEditor_AirDateFrom').value.strip() != '') ? ("ThisStartDate=\"" + ConvertToXMLDate($('comboEditor_AirDateFrom').value.strip()) + "\" ") : "";
            var thisEndDate = ($('comboEditor_AirDateTo').value.strip() != '') ? ("ThisEndDate=\"" + ConvertToXMLDate($('comboEditor_AirDateTo').value.strip()) + "\" ") : "";
            var duration = ($('comboEditor_Duration').value.strip() != '') ? ("Duration=\"" + ConvertToXMLDate($('comboEditor_Duration').value.strip()) + "\" ") : "";
            var colorRGB = $('comboEditor_Color').style.backgroundColor;
            colorRGB = colorRGB.substring(colorRGB.indexOf('(')+1, colorRGB.indexOf(')'));
            var rgbSplit = colorRGB.split(',');
            var color = rgb2hex(rgbSplit[0], rgbSplit[1], rgbSplit[2]);
            color = "ThisColor=\"" + color + "\" ";
            //var cueStringStart = ($('comboEditor_CueStringStart').value.strip() != '') ? ("CueStringStart=\"" + $('comboEditor_CueStringStart').value.strip() + "\" ") : "";

            // add video source to cue string start if exists
            var cueStringStartBase = "";
            var sourceSelect = $('comboEditor_VideoSource');
            if (sourceSelect.selectedIndex > 0) {
                cueStringStartBase = sourceSelect.options[sourceSelect.selectedIndex].value + ",";
            }
            
            var cueStringStart = "";
            if ($('comboEditor_CueStringStart').value.strip() != '') {
                cueStringStart = "CueStringStart=\"" + cueStringStartBase + escapeForXML($('comboEditor_CueStringStart').value.strip()) + "\" ";
            } else if (cueStringStartBase.length > 0) {
                cueStringStart = "CueStringStart=\"" + cueStringStartBase + "\" ";
            }
            
            var cueStringEnd = ($('comboEditor_CueStringEnd').value.strip() != '') ? ("CueStringEnd=\"" + escapeForXML($('comboEditor_CueStringEnd').value.strip()) + "\" ") : "";
            
            var dayPart = "ThisDayPart=\"" + getDPR() + "\" ";
            
            // var get text template id
            var templateSelect = $('comboEditorTemplateSelect');
            var templateSelectId = templateSelect.options[templateSelect.selectedIndex].value;
            templateSelectId = (templateSelectId > 0) ? ("TextTemplateID=\"" + templateSelectId + "\" ") : "";

            // set ingestednn and onplayersnn according to video source
            var channelSelect = $('comboEditor_Channel');
            var ingestedNNStr = "IngestedNN=\"false\" ";
            var onPlayersNNStr = "OnPlayersNN=\"false\" ";
            if (channelSelect.selectedIndex != 0) {
                var videoSourceSelect = $('comboEditor_VideoSource');
                if (videoSourceSelect.selectedIndex !=0) {
                    var videoSourceValue = videoSourceSelect.options[videoSourceSelect.selectedIndex].value;
                    if ( (channelSelect.options[channelSelect.selectedIndex].value == 1) ) { // Mitsubishi
                        var mitsuMatchValues = /10|11/;
                        if (videoSourceValue.search(mitsuMatchValues) < 0) {
                            ingestedNNStr = "IngestedNN=\"true\" ";
                            onPlayersNNStr = "OnPlayersNN=\"true\" ";
                        }
                    } else if (channelSelect.options[channelSelect.selectedIndex].value == 2) { // Ribbons
                        var ribbonsMatchValues = /30|33|34|47|54|61/;
                        if (videoSourceValue.search(ribbonsMatchValues) < 0) {
                            ingestedNNStr = "IngestedNN=\"true\" ";
                            onPlayersNNStr = "OnPlayersNN=\"true\" ";
                        }
                   } else if (channelSelect.options[channelSelect.selectedIndex].value == 3) { // Ticker
                        var tickersMatchValues = /70/;
                        if (videoSourceValue.search(tickersMatchValues) < 0) {
                            ingestedNNStr = "IngestedNN=\"true\" ";
                            onPlayersNNStr = "OnPlayersNN=\"true\" ";
                        }
                   }
                }
            }
           
            //xmlStr += "<BL_ASSET BLID=\"\" IsCombo=\"true\" ThisEnabled=\"true\" EnabledNN=\"true\" ";  WGO 2007-12-18: Removing enabled options
            xmlStr += "<BL_ASSET BLID=\"\" IsCombo=\"true\" ";
            xmlStr += thisEnabled + enabledNN + name + channel + thisStartDate + thisEndDate + duration + cueStringStart + cueStringEnd + templateSelectId + color + ingestedNNStr + onPlayersNNStr + dayPart + sessionIdBLStr + idBLStr;
            xmlStr += "/>";               
                        
            // get default combo
            if ($('comboEditor_DefaultCombo').checked) {
                var defaultChannel = "ChannelID=\"" + $('comboEditor_Channel').options[$('comboEditor_Channel').selectedIndex].value + "\" ";
                var defaultId = "ComboID=\"" + id + "\" ";
                xmlStr += "<BL_DEFAULTCOMBO BLID=\"\" ";
                xmlStr += sessionIdBLStr + defaultChannel + defaultId;
                xmlStr += "/>";       
            }                        
                                    
            // get metadata values
            var metaDataFields = $('comboEditorMetaData').getElementsByClassName('metadata');
            xmlStr += writeMDXML(metaDataFields, id);
            
            // get combovidlistspots
            var dataTagRules = $('comboEditor_DataTagRulesContainer').immediateDescendants();
            var count = 0;
            for (var i=0, len=dataTagRules.length; i<len; i++) {
                var matchValue = dataTagRules[i].getElementsBySelector('input[type="text"]')[0];
                var assetContainer = dataTagRules[i].getElementsByClassName('assetContainer')[0];
                if ( (matchValue.value.strip() != '') && (assetContainer.firstDescendant()) ) {
                    var baseStr = "<BL_COMBOVIDLISTSPOT BLID=\"\" ComboID=\"" + id + "\" ";
                    // get data tag rule values
                    var selects = dataTagRules[i].getElementsByTagName('select');
                    var index = "Index=\"" + (i+1) + "\" ";
                    var dataTagId = "DataTagID=\"" + selects[0].options[selects[0].selectedIndex].value + "\" ";
                    var comparator = "Comparator=\"" + selects[1].options[selects[1].selectedIndex].value + "\" ";
                    var matchValue = "MatchValue=\"" + escapeForXML(dataTagRules[i].getElementsBySelector('input[type="text"]')[0].value.strip()) + "\" ";
                    // get asset
                    var assetEl = dataTagRules[i].getElementsByClassName('assetContainer')[0].firstDescendant();
                    var assetId = "AssetID=\"" + activeEditor.getPeca(assetEl).dbId + "\" ";
                    
                    xmlStr += baseStr + assetId + index + dataTagId + comparator + matchValue + sessionIdBLStr;
                    xmlStr += "/>";
                    count++;
                }
            }
            
            // get default asset - required if count > 0
            if (count > 0) {
                var defaultAssetEl = $('comboEditorDefaultAsset').firstDescendant();
                var defaultAssetId = activeEditor.getPeca(defaultAssetEl).dbId;
                xmlStr += "<BL_COMBOVIDLISTSPOT BLID=\"\" ComboID=\"" + id + "\" Index=\"" + (count+1) + "\" AssetID=\"" + defaultAssetId + "\" " + sessionIdBLStr + "/>";
            } else if ( (count == 0) && ($('comboEditorDefaultAsset').firstDescendant()) ) {
                var defaultAssetEl = $('comboEditorDefaultAsset').firstDescendant();
                var defaultAssetId = activeEditor.getPeca(defaultAssetEl).dbId;
                xmlStr += "<BL_COMBOVIDLISTSPOT BLID=\"\" ComboID=\"" + id + "\" Index=\"" + (count+1) + "\" AssetID=\"" + defaultAssetId + "\" " + sessionIdBLStr + "/>";
            }
            
            // get text template strings - !!! Enhance
            var textStrings = $('comboEditorTextStrings').immediateDescendants();
            
            for (var i=0, len=textStrings.length; i<len; i++) {  
                var baseStr = "<BL_TEXTSTRING BLID=\"\" ComboID=\"" + id + "\" ";
                // get text string values
                var index = "Index=\"" + (i+1) + "\" ";
                //var textString = textStrings[i].getElementsByTagName('textarea')[0].value.strip(); WGO 11/26/07: Removing strip from text strings
                var textString = textStrings[i].getElementsByTagName('textarea')[0].value;
                
                // get an untainted version to replace textarea with
                var textStringEscapedTabsAndNewLines = textString;
                textStringEscapedTabsAndNewLines = textStringEscapedTabsAndNewLines.replace(/\n/g,"");
                textStringEscapedTabsAndNewLines = textStringEscapedTabsAndNewLines.replace(/\t/g,"");
                textStringEscapedTabsAndNewLines = textStringEscapedTabsAndNewLines.replace(/\r/g,"");
                
                // escape for xml
                textString = escapeForXML(textString);
                // replace nasty asciis with friendlier ones
                textString = replaceExtendedASCIIChars(textString);
                // escape newlines and tabs
                textString = textString.replace(/\n/g,"");
                textString = textString.replace(/\t/g,"");
                textString = textString.replace(/\r/g,"");  // not sure about this one yet
                var textStringBL = "String=\'" + textString + "\' ";
                                
                xmlStr += baseStr + index + textStringBL + sessionIdBLStr;
                xmlStr += "/>";  
                
                // assign textstring with escaped tabs and newlines back to textarea
                textStrings[i].getElementsByTagName('textarea')[0].value = textStringEscapedTabsAndNewLines;
                
            }

            xmlStr += "</ROOT>";
            url = "AjaxPost.aspx";
            saveEditorRequest.open('POST', url, true);
            saveEditorRequest.setRequestHeader("Content-Type", "text/xml");
            saveEditorRequest.send(xmlStr);	
            saveEditorRequest.onreadystatechange = processSaveEditorStateChange;	
            
        }  else if (activeEditor.systemLevel == 2) {  // save event
            // get event id
            var eventObj = eventRequest.responseXML.getElementsByTagName('EVENT')[0];
            var id = eventObj.getAttribute('ID');
            var idBLStr = (id != '') ? ("ID=\"" + id + "\" ") : ("ID=\"-1\" ");
        
            // create xml
            var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
            xmlStr += "<ROOT>";
     
            // assign stored procedure and set enabled for new objects
            if (id == -1) {
                xmlStr += "<STOREDPROCEDURE Name=\"sproc_WEB_InsertFromBLEvent\" />";
                eventObj.removeAttribute('ThisEnabled');
                eventObj.setAttribute('ThisEnabled', 1);
                eventObj.removeAttribute('EnabledNN');
                eventObj.setAttribute('EnabledNN', 1);
            } else {
                xmlStr += "<STOREDPROCEDURE Name=\"sproc_WEB_UpdateFromBLEvent\" />";
            }     

            // get enabled status and pass-through (both fields required)
            var thisEnabledValue = (eventObj.getAttribute('ThisEnabled') == 1) ? "true" : "false"; 
            var enabledNNValue = (eventObj.getAttribute('EnabledNN') == 1) ? "true" : "false";     
            var thisEnabled = "ThisEnabled=\"" + thisEnabledValue + "\" ";
            var enabledNN = "EnabledNN=\"" + enabledNNValue + "\" ";
 
//            var thisEnabledValue = (id == -1) ? "true" : (eventObj.getAttribute('ThisEnabled') == 1) ? "true" : "false"; 
//            var enabledNNValue = (id == -1) ? "true" : (eventObj.getAttribute('EnabledNN') == 1) ? "true" : "false"; 
//            var thisEnabled = "ThisEnabled=\"" + thisEnabledValue + "\" ";
//            var enabledNN = "EnabledNN=\"" + enabledNNValue + "\" ";          
     
            // get properties
            //var id = -1;  // id of -1 for new event
            var name = ($('eventEditor_Name').value.strip() != '') ? ("Name=\"" + escapeForXML($('eventEditor_Name').value.strip()) + "\" ") : "";
            //var zone = ($('eventEditor_Zone') != 0) ? ("ZoneID=\"" + "," + $('eventEditor_Zone').value + "," + "\" ") : "";
            var zone = "ZoneID=\"1\" "; 
            var thisStartDate = ($('eventEditor_AirDateFrom').value.strip() != '') ? ("ThisStartDate=\"" + ConvertToXMLDate($('eventEditor_AirDateFrom').value.strip()) + "\" ") : "";
            var thisEndDate = ($('eventEditor_AirDateTo').value.strip() != '') ? ("ThisEndDate=\"" + ConvertToXMLDate($('eventEditor_AirDateTo').value.strip()) + "\" ") : "";
            var duration = ($('eventEditor_Duration').value.strip() != '') ? ("Duration=\"" + ConvertToXMLDate($('eventEditor_Duration').value.strip()) + "\" ") : "";
            var colorRGB = $('eventEditor_Color').style.backgroundColor;
            colorRGB = colorRGB.substring(colorRGB.indexOf('(')+1, colorRGB.indexOf(')'));
            var rgbSplit = colorRGB.split(',');
            var color = rgb2hex(rgbSplit[0], rgbSplit[1], rgbSplit[2]);
            color = "ThisColor=\"" + color + "\" ";
            var cueStringStart = ($('eventEditor_CueStringStart').value.strip() != '') ? ("CueStringStart=\"" + escapeForXML($('eventEditor_CueStringStart').value.strip()) + "\" ") : "";
            var cueStringEnd = ($('eventEditor_CueStringEnd').value.strip() != '') ? ("CueStringEnd=\"" + escapeForXML($('eventEditor_CueStringEnd').value.strip()) + "\" ") : "";            
            
            var dayPart = "ThisDayPart=\"" + getDPR() + "\" ";
           
            //xmlStr += "<BL_EVENT BLID=\"\" ThisEnabled=\"true\" EnabledNN=\"true\" IngestedNN=\"false\" OnPlayersNN=\"false\" "; WGO 2007-12-18: Removing enabled options
            xmlStr += "<BL_EVENT BLID=\"\" IngestedNN=\"false\" OnPlayersNN=\"false\" ";
            xmlStr += thisEnabled + enabledNN + name + zone + thisStartDate + thisEndDate + duration + cueStringStart + cueStringEnd + color + dayPart + sessionIdBLStr + idBLStr;
            xmlStr += "/>";               
                        
            // get metadata values
            var metaDataFields = $('eventEditorMetaData').getElementsByClassName('metadata');
            xmlStr += writeMDXML(metaDataFields, id);
            
            // get event spots 
            var eventSpots = "";
            for (var i=0, len=activeEditor.ddLists.length; i<len; i++) {
                eventSpots += activeEditor.ddLists[i].saveItems();
            }
            xmlStr += eventSpots;
            
            // get cue strings 
           var cues = $('eventEditorCues').immediateDescendants();
           for (var i=0, len=cues.length; i<len; i++) {
                var time = cues[i].getElementsBySelector('input[type="text"]')[0];
                var cueString = cues[i].getElementsBySelector('input[type="text"]')[1];
                if (time && cueString) {
                    if ( (time.value.strip() != '') && (cueString.value.strip() != '') ) {
                        var baseStr = "<BL_EVENTSPOT BLID=\"\" EventID=\"" + id + "\" ";
                        var timeBl = "Time=\"" + ConvertToXMLDate(time.value.strip()) + "\" ";
                        var cueStringBL = "CueString=\"" + escapeForXML(cueString.value.strip()) + "\" ";
                        xmlStr += baseStr + timeBl + cueStringBL + sessionIdBLStr;
                        xmlStr += "/>";
                    }
                }

//                var timeSelect = cues[i].getElementsByTagName('select')[0];
//                var cueInput = cues[i].getElementsBySelector('input[type="text"]')[0].value.strip();
//                if (timeSelect.selectedIndex != 0 && cueInput != '') {
//                    var baseStr = "<BL_EVENTSPOT BLID=\"\" EventID=\"" + id + "\" ";
//                    var time = "Time=\"" + ConvertToXMLDate(timeSelect.options[timeSelect.selectedIndex].value) + "\" ";
//                    var cueString = "CueString=\"" + cueInput + "\" ";
//                    xmlStr += baseStr + time + cueString + sessionIdBLStr;
//                    xmlStr += "/>";
//                }
            }

            xmlStr += "</ROOT>";
            url = "AjaxPost.aspx";
            saveEditorRequest.open('POST', url, true);
            saveEditorRequest.setRequestHeader("Content-Type", "text/xml");
            saveEditorRequest.send(xmlStr);	
            saveEditorRequest.onreadystatechange = processSaveEditorStateChange;	
            
        } else if (activeEditor.systemLevel == 1) {  // save package
            // get package id
            var packageObj = packageRequest.responseXML.getElementsByTagName('PACKAGE')[0];
            var id = packageObj.getAttribute('ID');
            var idBLStr = (id != '') ? ("ID=\"" + id + "\" ") : ("ID=\"-1\" ");
        
            // create xml
            var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
            xmlStr += "<ROOT>";
     
            // assign stored procedure
            if (packageEditorPackageDate != '') {  // process a save package instance
                var inputs = $('savePackageInstance').getElementsByTagName('input');
                var dateFrom = "";
                var dateTo = "";
                if (inputs[0].checked) { // only this instance
                    var dateSplit = packageEditorPackageDate.split('/');
                    dateFrom = dateSplit[2] + "-" + parseInt(dateSplit[0],10).toPaddedString(2,10) + "-" + parseInt(dateSplit[1],10).toPaddedString(2,10) + "T" + packageEditorPackageTime + ":00";
                    dateTo = dateFrom;
                } else {  // instances in the range
                    dateFrom = ConvertToXMLDate($('savePackageDateFrom').value.strip());
                    dateTo = ConvertToXMLDate($('savePackageDateTo').value.strip());
                }
               xmlStr += "<STOREDPROCEDURE Name=\"sproc_WEB_SaveFromBLPackage\" dateFrom=\"" + dateFrom + "\" dateTo=\"" + dateTo + "\" />";
            } else {  // process a regular save
                if (id == -1) {  // new package
                    xmlStr += "<STOREDPROCEDURE Name=\"sproc_WEB_InsertFromBLPackage\" />";
                    packageObj.removeAttribute('ThisEnabled');
                    packageObj.setAttribute('ThisEnabled', 1);
                    packageObj.removeAttribute('EnabledNN');
                    packageObj.setAttribute('EnabledNN', 1);
                } else {  // update package
                    xmlStr += "<STOREDPROCEDURE Name=\"sproc_WEB_UpdateFromBLPackage\" />";
                }     
            }
            
            // get enabled status and pass-through (both fields required)
            var thisEnabledValue = (packageObj.getAttribute('ThisEnabled') == 1) ? "true" : "false"; 
            var enabledNNValue = (packageObj.getAttribute('EnabledNN') == 1) ? "true" : "false"; 
            var thisEnabled = "ThisEnabled=\"" + thisEnabledValue + "\" ";
            var enabledNN = "EnabledNN=\"" + enabledNNValue + "\" ";           
     
            // get properties
            //var id = -1;  // id of -1 for new package
            var name = ($('packageEditor_Name').value.strip() != '') ? ("Name=\"" + escapeForXML($('packageEditor_Name').value.strip()) + "\" ") : "";
            //var system = ($('packageEditor_System') != 0) ? ("SystemID=\"" + "," + $('packageEditor_System').value + "," + "\" ") : "";
            var thisStartDate = ($('packageEditor_AirDateFrom').value.strip() != '') ? ("ThisStartDate=\"" + ConvertToXMLDate($('packageEditor_AirDateFrom').value.strip()) + "\" ") : "";
            var thisEndDate = ($('packageEditor_AirDateTo').value.strip() != '') ? ("ThisEndDate=\"" + ConvertToXMLDate($('packageEditor_AirDateTo').value.strip()) + "\" ") : "";
            var duration = ($('packageEditor_Duration').value.strip() != '') ? ("Duration=\"" + ConvertToXMLDate($('packageEditor_Duration').value.strip()) + "\" ") : "";
            var colorRGB = $('packageEditor_Color').style.backgroundColor;
            colorRGB = colorRGB.substring(colorRGB.indexOf('(')+1, colorRGB.indexOf(')'));
            var rgbSplit = colorRGB.split(',');
            var color = rgb2hex(rgbSplit[0], rgbSplit[1], rgbSplit[2]);
            color = "ThisColor=\"" + color + "\" ";
            var cueStringStart = ($('packageEditor_CueStringStart').value.strip() != '') ? ("CueStringStart=\"" + escapeForXML($('packageEditor_CueStringStart').value.strip()) + "\" ") : "";
            var cueStringEnd = ($('packageEditor_CueStringEnd').value.strip() != '') ? ("CueStringEnd=\"" + escapeForXML($('packageEditor_CueStringEnd').value.strip()) + "\" ") : "";            
            
            var dayPart = "ThisDayPart=\"" + getDPR() + "\" ";
            var systemId = "SystemID=\"1\" ";
           
            //xmlStr += "<BL_PACKAGE BLID=\"\" ThisEnabled=\"true\" EnabledNN=\"true\" IngestedNN=\"false\" OnPlayersNN=\"false\" IsWebControlPackage=\"false\" "; WGO 2007-12-18: Removing enabled options
            xmlStr += "<BL_PACKAGE BLID=\"\" IngestedNN=\"false\" OnPlayersNN=\"false\" IsWebControlPackage=\"false\" ";
            xmlStr += thisEnabled + enabledNN + name + thisStartDate + thisEndDate + duration + cueStringStart + cueStringEnd + color + dayPart + systemId + sessionIdBLStr + idBLStr;
            xmlStr += "/>";               
                        
            // get metadata values
            var metaDataFields = $('packageEditorMetaData').getElementsByClassName('metadata');
            xmlStr += writeMDXML(metaDataFields, id);
            
            // get package spots
            var packageSpots = "";
            for (var i=0, len=activeEditor.ddLists.length; i<len; i++) {
                packageSpots += activeEditor.ddLists[i].saveItems();
            }
            xmlStr += packageSpots;
            
            // get cue strings
            var cues = $('packageEditorCues').immediateDescendants();
            for (var i=0, len=cues.length; i<len; i++) {
                var time = cues[i].getElementsBySelector('input[type="text"]')[0];
                var cueString = cues[i].getElementsBySelector('input[type="text"]')[1];
                if (time && cueString) {
                    if ( (time.value.strip() != '') && (cueString.value.strip() != '') ) {
                        var baseStr = "<BL_PACKAGESPOT BLID=\"\" PackageID=\"" + id + "\" ";
                        var timeBl = "Time=\"" + ConvertToXMLDate(time.value.strip()) + "\" ";
                        var cueStringBL = "CueString=\"" + escapeForXML(cueString.value.strip()) + "\" ";
                        xmlStr += baseStr + timeBl + cueStringBL + sessionIdBLStr;
                        xmlStr += "/>";
                    }
                }
            
//                var timeSelect = cues[i].getElementsByTagName('select')[0];
//                var cueInput = cues[i].getElementsBySelector('input[type="text"]')[0].value.strip();
//                if (timeSelect.selectedIndex != 0 && cueInput != '') {
//                    var baseStr = "<BL_PACKAGESPOT BLID=\"\" PackageID=\"" + id + "\" ";
//                    var time = "Time=\"" + ConvertToXMLDate(timeSelect.options[timeSelect.selectedIndex].value) + "\" ";
//                    var cueString = "CueString=\"" + cueInput + "\" ";
//                    xmlStr += baseStr + time + cueString + sessionIdBLStr;
//                    xmlStr += "/>";
//                }
            }

            xmlStr += "</ROOT>";
            url = "AjaxPost.aspx";
            saveEditorRequest.open('POST', url, true);
            saveEditorRequest.setRequestHeader("Content-Type", "text/xml");
            saveEditorRequest.send(xmlStr);	
            saveEditorRequest.onreadystatechange = processSaveEditorStateChange;	  
        } else if (activeEditor.systemLevel == 0) {  // save schedules
            // create xml
            var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
            xmlStr += "<ROOT>";
            
            // get schedule spots 
            var scheduledSpots = "";
            for (var i=0, len=activeEditor.ddLists.length; i<len; i++) {
                scheduledSpots += activeEditor.ddLists[i].saveItems();
            }
            xmlStr += scheduledSpots;      

            xmlStr += "</ROOT>";
            url = "AjaxPost.aspx";
            saveEditorRequest.open('POST', url, true);
            saveEditorRequest.setRequestHeader("Content-Type", "text/xml");
            saveEditorRequest.send(xmlStr);	
            saveEditorRequest.onreadystatechange = processSaveEditorStateChange;	
            
        }
    }
}

// function to show save copy as popup
function showSaveCopyAs () {
    $('saveCopyAlert').style.display = "none";
    var name = $('saveCopyName');
    // get current name and append something..
    // disable duration rows (used only for events)
    $('saveCopyDurationLabelRow').style.display = "none";
    $('saveCopyDurationRow').style.display = "none";
    if (activeEditor.systemLevel == 4) {
        name.value = $('assetEditor_Name').value.strip() + "_Copy";
    } else if (activeEditor.systemLevel == 3) {
        name.value = $('comboEditor_Name').value.strip() + "_Copy";
    } else if (activeEditor.systemLevel == 2) {
        name.value = $('eventEditor_Name').value.strip() + "_Copy";
        // enable duration rows
        $('saveCopyDurationLabelRow').style.display = "block";
        $('saveCopyDurationRow').style.display = "block";
        
        // clear duration select
        var durList = $('saveCopyDuration');
        var durOptions = durList.immediateDescendants();
        for (var i=0, len=durOptions.length; i<len; i++) {
            durOptions[i].remove();
        }
        // populate duration select
        var longestDur = getLongestDuration();
        var startDur = longestDur.split(':');
        var secondsInc = activeEditor.interval;
        var minutesInc = activeEditor.interval / 60;
		var startMinutes = parseInt(startDur[1],10);
		var startSeconds = parseInt(startDur[2],10);
		var curTime = startMinutes.toPaddedString(2,10) + ":" + startSeconds.toPaddedString(2,10);
		var counter = 0;
		var secondsOffset = startSeconds / secondsInc;
		while (curTime < "30:00") {
		//for (var i=0; i<activeEditor.numIntervals; i++) {		
			var timeStr = "";
			var minutes = Math.floor(startMinutes + minutesInc * (counter + secondsOffset)) % 60;
			var seconds = Math.floor(startSeconds + secondsInc * counter) % 60;
			timeStr += minutes.toPaddedString(2,10) + ":" + seconds.toPaddedString(2,10);
			curTime = timeStr;
			//if (padDurationStr(timeStr) >= longestDur) {
			// check that duration option is an increment of 15 seconds
            var durStr = padDurationStr(timeStr);
            var durSplit = durStr.split(':');
            var totalSeconds = (parseInt(durSplit[0],10) * 3600) + (parseInt(durSplit[1],10) * 60) + parseInt(durSplit[2],10);
            if ( (totalSeconds % 15) == 0 ) {
			    var timeOption = document.createElement('option');
			    timeOption.value = timeStr;
			    timeOption.text = timeStr;
			    durList.options.add(timeOption);
			}
			//}
			counter++;
		}
        // add final option because it's not in time slots list
//        var optionEl = document.createElement('option');
//        optionEl.value = "30:00";
//        optionEl.text = "30:00";
//        durList.options.add(optionEl);  
    } else if (activeEditor.systemLevel == 1) {
        name.value = $('packageEditor_Name').value.strip() + "_Copy";
    }
    // display the popup
    $('saveCopyAsPopup').style.display = "block";
    coverPageForAlert($('saveCopyAsPopup'));
}

// function to hide save copy as popup
function hideSaveCopyAs () {
    uncoverPageForAlert();
    $('saveCopyAsPopup').style.display = "none";
}

// function to proceed with save copy
function saveCopyAs() {
    var errMsg = "";
    // check required fields
    if ($('saveCopyName').value.strip() == '') {
        if (activeEditor.systemLevel == 1) errMsg = "&#149; Package name is a required field"
        else if (activeEditor.systemLevel == 2) errMsg = "&#149; Event name is a required field"
        else if (activeEditor.systemLevel == 3) errMsg = "&#149; Combo name is a required field"
        else if (activeEditor.systemLevel == 4) errMsg = "&#149; Asset name is a required field"
    }
    if (errMsg != '') {
        var alertEl = $('saveCopyAlert');
        alertEl.innerHTML = errMsg;
        $('saveCopyAlert').style.display = "block";
        return;
    }

    var newName = $('saveCopyName').value.strip();
    // update name field on form and reset id to -1 in xml, then do an insert
    if (activeEditor.systemLevel == 4) {  // asset
        // check for unique name
        if (!checkUniqueName (-1, $('saveCopyName').value.strip(), 4)) {
            var alertEl = $('saveCopyAlert');
            errMsg = "&#149; An asset with this name already exists<br />"
            alertEl.innerHTML = errMsg;
            var name = $('saveCopyName').value.strip();
            $('saveCopyName').value = name + "_";
            $('saveCopyAlert').style.display = "block";
            return;
        }
        // validate form again before proceeding
        var originalName = $('assetEditor_Name').value.strip();
        $('assetEditor_Name').value = newName;
        if (!validateForm()) {
            var alertEl = $('saveCopyAlert');
            errMsg = "&#149; There are errors on the form below.  Please correct before saving a copy.<br />"
            alertEl.innerHTML = errMsg;
            $('assetEditor_Name').value = originalName;
            $('saveCopyAlert').style.display = "block";
            return;
        }
        
        var asset = assetRequest.responseXML.getElementsByTagName('ASSET')[0];
        // close current before saving copy
        objForEditClose();
        // reset id for new save
        asset.removeAttribute('ID');
        asset.setAttribute('ID', -1);
    } else if (activeEditor.systemLevel == 3) {  // combo
        // check for unique name
        if (!checkUniqueName (-1, $('saveCopyName').value.strip(), 3)) {
            var alertEl = $('saveCopyAlert');
            errMsg = "&#149; A combo with this name already exists"
            alertEl.innerHTML = errMsg;
            var name = $('saveCopyName').value.strip();
            $('saveCopyName').value = name + "_";
            $('saveCopyAlert').style.display = "block";
            return;
        }
        // validate form again before proceeding
        var originalName = $('comboEditor_Name').value.strip();
        $('comboEditor_Name').value = newName;
        if (!validateForm()) {
            var alertEl = $('saveCopyAlert');
            errMsg = "&#149; There are errors on the form below.  Please correct before saving a copy.<br />"
            alertEl.innerHTML = errMsg;
            $('comboEditor_Name').value = originalName;
            $('saveCopyAlert').style.display = "block";
            return;
        }
        
        var combo = comboRequest.responseXML.getElementsByTagName('ASSET')[0];
        // close current before saving copy
        objForEditClose();
        // reset id for new save
        combo.removeAttribute('ID');
        combo.setAttribute('ID', -1);
    } else if (activeEditor.systemLevel == 2) {  // event
        // check for unique name
        if (!checkUniqueName (-1, $('saveCopyName').value.strip(), 2)) {
            var alertEl = $('saveCopyAlert');
            errMsg = "&#149; An event with this name already exists"
            alertEl.innerHTML = errMsg;
            var name = $('saveCopyName').value.strip();
            $('saveCopyName').value = name + "_";
            $('saveCopyAlert').style.display = "block";
            return;
        }
        // validate form again before proceeding
        var originalName = $('eventEditor_Name').value.strip();
        $('eventEditor_Name').value = newName;
        if (!validateForm()) {
            var alertEl = $('saveCopyAlert');
            errMsg = "&#149; There are errors on the form below.  Please correct before saving a copy.<br />"
            alertEl.innerHTML = errMsg;
            $('eventEditor_Name').value = originalName;
            $('saveCopyAlert').style.display = "block";
            return;
        }
        
        var durList = $('saveCopyDuration');
        $('eventEditor_Duration').value = durList.options[durList.selectedIndex].value;
        // set global to avoid validating the duration again
        eventEditorDurationUpdated = true;
        var eventObj = eventRequest.responseXML.getElementsByTagName('EVENT')[0];
        // close current before saving copy
        objForEditClose();
        // reset id for new save
        eventObj.removeAttribute('ID');
        eventObj.setAttribute('ID', -1);
    } else if (activeEditor.systemLevel == 1) {  // package
        // check for unique name
        if (!checkUniqueName (-1, $('saveCopyName').value.strip(), 1)) {
            var alertEl = $('saveCopyAlert');
            errMsg = "&#149; A package with this name already exists"
            alertEl.innerHTML = errMsg;
            var name = $('saveCopyName').value.strip();
            $('saveCopyName').value = name + "_";
            $('saveCopyAlert').style.display = "block";
            return;
        }
        // validate form again before proceeding
        var originalName = $('packageEditor_Name').value.strip();
        $('packageEditor_Name').value = newName;
        if (!validateForm()) {
            var alertEl = $('saveCopyAlert');
            errMsg = "&#149; There are errors on the form below.  Please correct before saving a copy.<br />"
            alertEl.innerHTML = errMsg;
            $('packageEditor_Name').value = originalName;
            $('saveCopyAlert').style.display = "block";
            return;
        }
        
        var packageObj = packageRequest.responseXML.getElementsByTagName('PACKAGE')[0];
        // close current before saving copy
        objForEditClose();
        // reset id for new save
        packageObj.removeAttribute('ID');
        packageObj.setAttribute('ID', -1);
    }
    // run save editor to insert new object
    hideSaveCopyAs(); 
    saveEditorObject();
}

// function to show the dialog for saving a scheduled package
function showSavePackageInstance() {
    // reset popup
    $('savePackageAlert').style.display = "none";
    var inputs = $('savePackageInstance').getElementsByTagName('input');
    inputs[0].checked = true;
    inputs[1].checked = false;
    // populate name field
    $('savePackageName').value = $('packageEditor_Name').value.strip() + "_";
    // populate date field with date of scheduled package
    $('savePackageDateFrom').value = packageEditorPackageDate;
    $('savePackageDateTo').value = "";

    $('savePackageInstance').style.display = 'block'
    coverPageForAlert($('savePackageInstance'));
}

function updateSavePackageOptions() {
    var inputs = $('savePackageInstance').getElementsByTagName('input');
    inputs[0].checked = false;
    inputs[1].checked = true;    
}

function hideSavePackageInstance () {
    uncoverPageForAlert();
    $('savePackageInstance').style.display = "none";
}

var savePackageInstanceRequest = new XMLHttpRequest();
// make request to save package instance
function requestSavePackageInstance() { 
    // get package id
    var packageObj = packageRequest.responseXML.getElementsByTagName('PACKAGE')[0];
    var id = packageObj.getAttribute('ID');
    var errMsg = "";
    // check required fields
    if ($('savePackageName').value.strip() == '')
        errMsg += "&#149; Package name is a required field<br />";
    var inputs = $('savePackageInstance').getElementsByTagName('input');
    if (inputs[1].checked) {
        if ($('savePackageDateFrom').value.strip() == '')
            errMsg += "&#149; You must choose a start date for this option<br />";
        if ($('savePackageDateTo').value.strip() == '')
            errMsg += "&#149; You must choose an end date for this option<br />";
    }
    if (errMsg != '') {
        var alertEl = $('savePackageAlert');
        alertEl.innerHTML = errMsg;
        $('savePackageAlert').style.display = "block";
        return;
    }
    
    // check unique name and proper dates
    if (!checkUniqueName (-1, $('savePackageName').value.strip(), 1)) {  // -1 for name check since this is for a new instance
        errMsg = "&#149; A package with this name already exists";
        var name = $('savePackageName').value.strip();
        $('savePackageName').value = name + "_";
    }
    if (inputs[1].checked) {
        if ( !($('savePackageDateFrom').value.strip().match(dateRegex)) )
            errMsg = "&#149; The start date is not formatted correctly<br />";
        if ( !($('savePackageDateTo').value.strip().match(dateRegex)) )
            errMsg = "&#149; The end date is not formatted correctly<br />";
    }
    if (errMsg != '') {
        var alertEl = $('savePackageAlert');
        alertEl.innerHTML = errMsg;
        $('savePackageAlert').style.display = "block";
        return;
    }
    
    // change name on package form to new name and try to save the package
    $('packageEditor_Name').value = $('savePackageName').value.strip();
    hideSavePackageInstance(); 
    saveEditorObject();
}

// function to make request to see if a name is unique
var uniqueNameRequest = new XMLHttpRequest();	
function checkUniqueName (id, objectName, level) {
    // make request to db
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_DoesNameExist\" ObjectName=\"" + escapeForXML(objectName) + "\" Level=\"" + level + "\" />";
    //callAjaxPost(uniqueNameRequest, sProc, processValidateUniqueNameStateChange);
    
    // create xml
    var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
    xmlStr += "<ROOT>";
    xmlStr += sProc;
    xmlStr += "</ROOT>";
    url = "AjaxPost.aspx";
    uniqueNameRequest.open('POST', url, false);
    uniqueNameRequest.setRequestHeader("Content-Type", "text/xml");
    uniqueNameRequest.send(xmlStr);
    
    var response = uniqueNameRequest.responseText;
    if (id > 0) { // this is an update a
        if (response != 0) { // this means we found a match
            return (response == id) ? true : false;
        } else {  // no match, so name is unique
            return true;
        }
    } else { // handle inserts
        return (response == 0) ? true : false;
    }
}

var packageAlertRequest = new XMLHttpRequest();
// function to request package alerts
function requestPackageAlerts () {
    var selected = activeEditor.selectedCell;
    var packageNode = selected.firstDescendant();
    var activePeca = activeEditor.getPeca(packageNode);
    
    // get list index and it's date
    var listIndex = parseInt(selected.id.substr(selected.id.indexOf('ddList_') + 7),10);
    var dropDateStr = activeEditor.listLookupIds[listIndex];
    var dateSplit = dropDateStr.split('/');
    var dateArr = [dateSplit[2], dateSplit[0], dateSplit[1]];
    dropDateStr = dateArr[0] + "-" + parseInt(dateArr[1],10).toPaddedString(2,10) + "-" + parseInt(dateArr[2],10).toPaddedString(2,10);
    // get drop's time 
    var selectedId = selected.id;
    var dropIndex = parseInt(selectedId.substr(selectedId.indexOf('drop_') + 5),10);
    var dropTimeStr = activeEditor.timeSlots[dropIndex];  // hh:mm
    var dropDateTimeStr = dropDateStr + "T" + dropTimeStr;
    
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_PackageAlertReport\" PackageID=\"" + activePeca.dbId + "\" CheckDateTime=\"" + dropDateTimeStr + "\" />";
    callAjaxPost(packageAlertRequest, sProc, processPackageAlertRequest);	
}

// ajax state change handler
function processPackageAlertRequest () {
	if (packageAlertRequest.readyState == 4) {
		if (packageAlertRequest.status == 200) {
		    if (packageAlertRequest.responseXML != null) viewPackageAlerts();
		}
	} 
}

// function to view package alerts
//function viewPackageAlerts () {  !!! WGO OLD VERSION
//    var container = $('packageAlertInner');
//    // clear out any previous report
//    var prevLines = container.immediateDescendants();
//    for (var i=0, len=prevLines.length; i<len; i++) {
//        prevLines[i].remove();
//    }

//    // get new report and append to container
//    var reports = packageAlertRequest.responseXML.getElementsByTagName('Report');
//    for (var i=0, len=reports.length; i<len; i++) {
//        var row = document.createElement('div');
//        row.className = "row";
//        row.innerHTML = reports[i].getAttribute('Line');
//        if (i == 0) row.style.fontWeight = "bold";
//        container.appendChild(row);
//    }
//    //var height = $('packageAlertPopup').getHeight();
//    //$('packageAlertPopup').style.height = (height > 600) ? "600px" : (height + "px");
//    $('packageAlertPopup').style.display = "block";
//}

function lvl2Str (level) {
    if (level == 1) return "Package";
    if (level == 2) return "Event";
    if (level == 3) return "Combo";
    if (level == 4) return "Asset";
}

function renderAlerts (nodes, level, parentId, parentLevel, spacing, showAll) {
    // stop condition
    if (level == 5) return null;
    
    // get children at this level
    var children = [];
    for (var i=0, len=nodes.length; i<len; i++) {
        if ( (nodes[i].getAttribute('Level') == level) && (nodes[i].getAttribute('ParentID') == parentId) 
            && (nodes[i].getAttribute('ParentLevel') == parentLevel) )
            children.push(nodes[i]);
    }
   
    var container = document.createElement('div');
    var newSpacing = parseInt(spacing,10)+10;
    for (var i=0, len=children.length; i<len; i++) {
        // create row
        var row = document.createElement('div');
        row.className = "row";
        var id = children[i].getAttribute('ID');
        var name = children[i].getAttribute('Name');
        row.style.paddingLeft = newSpacing + "px";
        row.innerHTML = "&#149; " + lvl2Str(level) + ": " + name + " (id=" + id + ")";
        var alert = children[i].getAttribute('Alert');
        var conflictId = parseInt(children[i].getAttribute('ConflictID'),10);
        if (alert && alert == true && conflictId < 3) row.style.color = "Red";
        if (alert && alert == true && conflictId > 2) { row.style.color = "#E5B70E"; row.style.fontWeight = "bold"; }
        if (!(level == 4 && alert == false))
            container.appendChild(row);
        // get children
        var childElements = renderAlerts(nodes,(parseInt(level,10)+1),id, level, newSpacing, showAll);
        if (childElements) container.appendChild(childElements);
        if (level == 2) { // look two levels down for assets
            var secondChildElements = renderAlerts(nodes,(parseInt(level,10)+2),id, level, newSpacing, showAll);
            if (secondChildElements) container.appendChild(secondChildElements);
        }
    }
    return container;
}

function viewPackageAlerts () {
    var container = $('packageAlertInner');
    container.style.padding = "5px";
    // clear out any previous report
    var prevLines = container.immediateDescendants();
    for (var i=0, len=prevLines.length; i<len; i++) {
        prevLines[i].remove();
    }

    // get conflicts and nodes for each type
    var conflicts = packageAlertRequest.responseXML.getElementsByTagName('Conflict');
    var enabled = [];
    var ingested = [];
    var onPlayers = [];
    var startDate = [];
    var endDate = [];
    var dayPart = [];
    for (var i=0, len=conflicts.length; i<len; i++) {
        if (conflicts[i].getAttribute('ConflictID') == 0)
            enabled.push(conflicts[i]);
        if (conflicts[i].getAttribute('ConflictID') == 1)
            ingested.push(conflicts[i]);
        if (conflicts[i].getAttribute('ConflictID') == 2)
            onPlayers.push(conflicts[i]);
        if (conflicts[i].getAttribute('ConflictID') == 3)
            startDate.push(conflicts[i]);
        if (conflicts[i].getAttribute('ConflictID') == 4)
            endDate.push(conflicts[i]);
        if (conflicts[i].getAttribute('ConflictID') == 5)
            dayPart.push(conflicts[i]);
    }
    
    // get top level package info
    var selected = activeEditor.selectedCell;
    var packageNode = selected.firstDescendant();
    var activePeca = activeEditor.getPeca(packageNode);
    var packageId = activePeca.dbId;
    
    // get list index and it's date
    var listIndex = parseInt(selected.id.substr(selected.id.indexOf('ddList_') + 7),10);
    var dropDateStr = activeEditor.listLookupIds[listIndex];
//    var dateSplit = dropDateStr.split('/');
//    var dateArr = [dateSplit[2], dateSplit[0], dateSplit[1]];
//    dropDateStr = dateArr[0] + "-" + parseInt(dateArr[1],10).toPaddedString(2,10) + "-" + parseInt(dateArr[2],10).toPaddedString(2,10);
    // get drop's time 
    var selectedId = selected.id;
    var dropIndex = parseInt(selectedId.substr(selectedId.indexOf('drop_') + 5),10);
    var dropTimeStr = activeEditor.timeStrs[dropIndex];  // hh:mm
    
    if (enabled.length > 0) {
        var row = document.createElement('div');
        row.className = "row";
        row.style.fontWeight = "bold";
        row.innerHTML = "&#149; Scheduled items that are currently not enabled";
        container.appendChild(row);
        if (enabled[0].getAttribute('Level') == 1) {
            var row = document.createElement('div');
            row.className = "row";
            var id = enabled[0].getAttribute('ID');
            var name = enabled[0].getAttribute('Name');
            row.style.paddingLeft = 10 + "px";
            row.innerHTML = "&#149; " + lvl2Str(1) + ": " + name + " (id=" + id + ")";
            container.appendChild(row);
        }
        var childElements = renderAlerts(enabled, 2, packageId, 1, 10, true);
        if (childElements) container.appendChild(childElements);
    }
    
    if (ingested.length > 0) {
        var row = document.createElement('div');
        row.className = "row";
        row.style.fontWeight = "bold";
        row.innerHTML = "&#149; Scheduled assets that are currently not ingested";
        container.appendChild(row);
        var childElements = renderAlerts(ingested, 2, packageId, 1, 10, false);
        if (childElements) container.appendChild(childElements);
    }
    
    if (onPlayers.length > 0) {
        var row = document.createElement('div');
        row.className = "row";
        row.style.fontWeight = "bold";
        row.innerHTML = "&#149; Scheduled assets that are currently not on players";
        container.appendChild(row);
        var childElements = renderAlerts(onPlayers, 2, packageId, 1, 10, false);
        if (childElements) container.appendChild(childElements);
    }
    
    if (startDate.length > 0) {
        var row = document.createElement('div');
        row.className = "row";
        row.style.fontWeight = "bold";
        row.innerHTML = "&#149; Scheduled items with start dates after " + dropDateStr;
        container.appendChild(row);
        if (startDate[0].getAttribute('Level') == 1) {
            var row = document.createElement('div');
            row.className = "row";
            var id = startDate[0].getAttribute('ID');
            var name = startDate[0].getAttribute('Name');
            row.style.paddingLeft = 10 + "px";
            row.innerHTML = "&#149; " + lvl2Str(1) + ": " + name + " (id=" + id + ")";
            container.appendChild(row);
        }
        var childElements = renderAlerts(startDate, 2, packageId, 1, 10, true);
        if (childElements) container.appendChild(childElements);
    }
    
    if (endDate.length > 0) {
        var row = document.createElement('div');
        row.className = "row";
        row.style.fontWeight = "bold";
        row.innerHTML = "&#149; Scheduled items with end dates before " + dropDateStr;
        container.appendChild(row);
        if (endDate[0].getAttribute('Level') == 1) {
            var row = document.createElement('div');
            row.className = "row";
            var id = endDate[0].getAttribute('ID');
            var name = endDate[0].getAttribute('Name');
            row.style.paddingLeft = 10 + "px";
            row.innerHTML = "&#149; " + lvl2Str(1) + ": " + name + " (id=" + id + ")";
            container.appendChild(row);
        }
        var childElements = renderAlerts(endDate, 2, packageId, 1, 10, true);
        if (childElements) container.appendChild(childElements);
    }
    
    if (dayPart.length > 0) {
        var row = document.createElement('div');
        row.className = "row";
        row.style.fontWeight = "bold";
        row.innerHTML = "&#149; Scheduled items that should not be scheduled at " + dropTimeStr;
        container.appendChild(row);
        if (dayPart[0].getAttribute('Level') == 1) {
            var row = document.createElement('div');
            row.className = "row";
            var id = dayPart[0].getAttribute('ID');
            var name = dayPart[0].getAttribute('Name');
            row.style.paddingLeft = 10 + "px";
            row.innerHTML = "&#149; " + lvl2Str(1) + ": " + name + " (id=" + id + ")";
            container.appendChild(row);
        }
        var childElements = renderAlerts(dayPart, 2, packageId, 1, 10, true);
        if (childElements) container.appendChild(childElements);
    }
    
    //var height = $('packageAlertPopup').getHeight();
    //$('packageAlertPopup').style.height = (height > 600) ? "600px" : (height + "px");
    $('packageAlertPopup').style.display = "block";
}

// global regular expressions
var durationRegex = /(^[0-2]?\d:[0-5]\d:[0-5]\d$)|(^[0-5]?\d:[0-5]\d$)|(^[0-5]?\d$)/;
var dateRegex = /(^[0-1]?\d\/[0-3]?\d\/\d{2}$)|(^[0-1]?\d\/[0-3]?\d\/\d{4}$)/;
var intRegex = /^\d{1,10}$/;
var decimalRegex = /(^\d+\.\d+$)|(^\d{1,10}$)/;
var timeRegex = /(^[0-2]?\d:[0-5]\d:[0-5]\d$)|(^[0-5]?\d:[0-5]\d$)|(^[0-5]?\d$)|(^[0-1]?\d:[0-5]\d\s?((am)|(AM)|(pm)|(PM))?$)/;
var invalidCueStrRegex = /\"|\(.*\,.*\)/

// function to validate a form before saving
function validateForm () {
    var xml = null;
    var msgNode = null;
    var errMsg = "";
    if (activeEditor.systemLevel == 4) { // validate asset
        // initialize
        xml = assetRequest.responseXML;
        msgNode = $('assetEditor_Messages');
        // clear message node
        msgNode.style.display = "none";
        msgNode.style.color = "Red";
        msgNode.innerHTML = "";
        
        // check required fields
        if ($('assetEditor_Name').value.strip() == '') 
            errMsg += "&#149; Asset name is a required field<br />";
        if ($('assetEditor_Duration').value.strip() == '') 
            errMsg += "&#149; Asset duration is a required field<br />";
        if ($('assetEditor_Channel').selectedIndex < 1) 
            errMsg += "&#149; Display surface is a required field<br />";
        if ($('assetEditor_VideoSource').selectedIndex < 1) 
            errMsg += "&#149; Video source is a required field<br />";
        
        // stop and alert if errors
        if (errMsg != '') {
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }
        
        // get id to see if this is an update
        var asset = xml.getElementsByTagName('ASSET')[0];
        var assetId = asset.getAttribute('ID');
        
        // check if name is unique
        if (!checkUniqueName(assetId, $('assetEditor_Name').value.strip(), 4)) {
        //if (!checkUniqueName(assetId, nameValueStr, 4)) {
            errMsg += "&#149; An asset with this name already exists<br />";
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }
        
        // validate duration and make sure it is at least 3 secs
        if (!($('assetEditor_Duration').value.strip().match(durationRegex))) {
            errMsg += "&#149; Asset duration is not formatted correctly<br />";
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }
        
        var assetDurationStr = padDurationStr($('assetEditor_Duration').value.strip());
        if ( assetDurationStr < '00:00:03' ) {
            errMsg += "&#149; Asset duration must be at least 3 seconds long<br />";
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }
        
        // validate static fields  
        // air dates
        if (($('assetEditor_AirDateFrom').value.strip() != '') && !($('assetEditor_AirDateFrom').value.strip().match(dateRegex)))
            errMsg += "&#149; Air date start is not formatted correctly<br />";
        if (($('assetEditor_AirDateTo').value.strip() != '') && !($('assetEditor_AirDateTo').value.strip().match(dateRegex)))
            errMsg += "&#149; Air date end is not formatted correctly<br />";
        
        // cue strings
        if (($('assetEditor_CueStringStart').value.strip() != '') && ($('assetEditor_CueStringStart').value.match(invalidCueStrRegex)))
            errMsg += "&#149; Cue string start cannot contain double quotes or commas within parentheses<br />";
        if (($('assetEditor_CueStringEnd').value.strip() != '') && ($('assetEditor_CueStringEnd').value.match(invalidCueStrRegex)))
            errMsg += "&#149; Cue string end cannot contain double quotes or commas within parentheses<br />";
            
        // validate metadata fields
        errMsg += validateMDFields(xml, msgNode);
        
    } else if (activeEditor.systemLevel == 3) { // validate combo
        // initialize
        xml = comboRequest.responseXML;
        msgNode = $('comboEditor_Messages');
        // clear message node
        msgNode.style.display = "none";
        msgNode.style.color = "Red";
        msgNode.innerHTML = "";
        
        // check required fields
        if ($('comboEditor_Name').value.strip() == '') 
            errMsg += "&#149; Combo name is a required field<br />";
        if ($('comboEditor_Duration').value.strip() == '') 
            errMsg += "&#149; Combo duration is a required field<br />";
        if ($('comboEditor_Channel').selectedIndex < 1) 
            errMsg += "&#149; Display surface is a required field<br />";
        
        // video source required if no default asset
        var defaultAssetCheck = $('comboEditorDefaultAsset');
        if (!defaultAssetCheck.firstDescendant()) {
            if ($('comboEditor_VideoSource').selectedIndex < 1) 
                errMsg += "&#149; Video source is a required field if there is no default asset<br />";
        } else if (defaultAssetCheck.firstDescendant()) { // can't have both
            if ($('comboEditor_VideoSource').selectedIndex > 0) 
                errMsg += "&#149; You cannot select a video source and a default asset at the same time<br />";
        }
        
        
        // stop and alert if errors
        if (errMsg != '') {
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }
        
        // get id to see if this is an update
        var combo = xml.getElementsByTagName('ASSET')[0];
        var comboId = combo.getAttribute('ID');
        
        // check if name is unique
        if (!checkUniqueName(comboId, $('comboEditor_Name').value.strip(), 3)) {
            errMsg += "&#149; A combo with this name already exists<br />";
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }
        
        
        // validate duration and make sure it is at least 3 secs
        if (!($('comboEditor_Duration').value.strip().match(durationRegex))) {
            errMsg += "&#149; Combo duration is not formatted correctly<br />";
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }
        
        var comboDurationStr = padDurationStr($('comboEditor_Duration').value.strip());
        if ( comboDurationStr < '00:00:03' ) {
            errMsg += "&#149; Combo duration must be at least 3 seconds long<br />";
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }        
        
        // validate static fields  
        // air dates
        if (($('comboEditor_AirDateFrom').value.strip() != '') && !($('comboEditor_AirDateFrom').value.strip().match(dateRegex)))
            errMsg += "&#149; Air date start is not formatted correctly<br />";
        if (($('comboEditor_AirDateTo').value.strip() != '') && !($('comboEditor_AirDateTo').value.strip().match(dateRegex)))
            errMsg += "&#149; Air date end is not formatted correctly<br />";
        
        // cue strings
        if (($('comboEditor_CueStringStart').value.strip() != '') && ($('comboEditor_CueStringStart').value.match(invalidCueStrRegex)))
            errMsg += "&#149; Cue string start cannot contain double quotes or commas within parentheses<br />";
        if (($('comboEditor_CueStringEnd').value.strip() != '') && ($('comboEditor_CueStringEnd').value.match(invalidCueStrRegex)))
            errMsg += "&#149; Cue string end cannot contain double quotes or commas within parentheses<br />";
            
        // validate metadata fields
        errMsg += validateMDFields(xml, msgNode);
        
        // validate assets and tag associations
        var dataTagRules = $('comboEditor_DataTagRulesContainer').immediateDescendants();
        var isIncomplete = false;
        var noRules = false;
        if (dataTagRules.length == 0) noRules = true;
        for (var i=0, len=dataTagRules.length; i<len; i++) {
            var matchValue = dataTagRules[i].getElementsBySelector('input[type="text"]')[0];
            var assetContainer = dataTagRules[i].getElementsByClassName('assetContainer')[0];
            if (len == 1) {
                if ( (matchValue.value.strip() == '') && (!assetContainer.firstDescendant()) ) {
                    noRules = true;
                    break;
                }
            }
            if ( ( (matchValue.value.strip() == '') && (assetContainer.firstDescendant()) )
                    || ( (matchValue.value.strip() != '') && (!assetContainer.firstDescendant()) ) ) {
                isIncomplete = true;
            }
        }
        
       if (isIncomplete) {
            errMsg += "&#149; One or more data tag rules is missing a comparison value or asset<br />";
        } else if (!noRules) {
            // check for default asset
            var defaultAsset = $('comboEditorDefaultAsset');
            if (!defaultAsset.firstDescendant()) {
                errMsg += "&#149; You must specify a default asset along with the data tag rules<br />";
            }
        }
    } else if (activeEditor.systemLevel == 2) { // validate event
        // initialize
        xml = eventRequest.responseXML;
        msgNode = $('eventEditor_Messages');
        // clear message node
        msgNode.style.display = "none";
        msgNode.style.color = "Red";
        msgNode.innerHTML = "";
        
        // check required fields
        if ($('eventEditor_Name').value.strip() == '') 
            errMsg += "&#149; Event name is a required field<br />";
        if ($('eventEditor_Duration').value.strip() == '') 
            errMsg += "&#149; Event duration is a required field<br />";
        
        // stop and alert if errors
        if (errMsg != '') {
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }
        
        // get id to see if this is an update
        var eventObj = xml.getElementsByTagName('EVENT')[0];
        var eventId = eventObj.getAttribute('ID');
        
        // check if name is unique
        if (!checkUniqueName(eventId, $('eventEditor_Name').value.strip(), 2)) {
            errMsg += "&#149; An event with this name already exists<br />";
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }
        
        // check that duration is an increment of 15 seconds
        var durStr = padDurationStr($('eventEditor_Duration').value.strip());
        var durSplit = durStr.split(':');
        var totalSeconds = (parseInt(durSplit[0],10) * 3600) + (parseInt(durSplit[1],10) * 60) + parseInt(durSplit[2],10);
        if ( (totalSeconds % 15) != 0 ) {
            errMsg += "&#149; Event durations must be in increments of 15 seconds<br />";
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }        
        
        // get longest list duration
        var durationStr = padDurationStr($('eventEditor_Duration').value.strip());
        var longestDurationStr = getLongestDuration();
        
        // check duration       
        if (longestDurationStr > durationStr) {
            errMsg += "&#149; One of the event lists exceeds the current duration<br />";
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        } 
        
        // validate static fields  
        // duration
        if (!($('eventEditor_Duration').value.strip().match(durationRegex)))
            errMsg += "&#149; Event duration is not formatted correctly<br />";
        // air dates
        if (($('eventEditor_AirDateFrom').value.strip() != '') && !($('eventEditor_AirDateFrom').value.strip().match(dateRegex)))
            errMsg += "&#149; Air date start is not formatted correctly<br />";
        if (($('eventEditor_AirDateTo').value.strip() != '') && !($('eventEditor_AirDateTo').value.strip().match(dateRegex)))
            errMsg += "&#149; Air date end is not formatted correctly<br />";

        // cue strings
        if (($('eventEditor_CueStringStart').value.strip() != '') && ($('eventEditor_CueStringStart').value.match(invalidCueStrRegex)))
            errMsg += "&#149; Cue string start cannot contain double quotes or commas within parentheses<br />";
        if (($('eventEditor_CueStringEnd').value.strip() != '') && ($('eventEditor_CueStringEnd').value.match(invalidCueStrRegex)))
            errMsg += "&#149; Cue string end cannot contain double quotes or commas within parentheses<br />";
            

         // validate metadata fields
        errMsg += validateMDFields(xml, msgNode);   
        
        // validate cue strings
        var cues = $('eventEditorCues').immediateDescendants();
        var isIncomplete = false;
        var isOutOfRange = false;
        var isInvalid = false;
        for (var i=0, len=cues.length; i<len; i++) {
            var time = cues[i].getElementsBySelector('input[type="text"]')[0];
            var cueString = cues[i].getElementsBySelector('input[type="text"]')[1];
            if (time && cueString) {
                if ( ( (cueString.value.strip() == '') && (time.value.strip() != '') )
                        || ( (cueString.value.strip() != '') && (time.value.strip() == '') ) ) {
                    isIncomplete = true;
                }
                if (time.value.strip() != '') {
                    var timeValue = padDurationStr(time.value.strip());
                    if (timeValue > durationStr) isOutOfRange = true;
                }
                if (cueString.value.match(invalidCueStrRegex)) isInvalid = true;
            }
        }
        if (isIncomplete) {
            errMsg += "&#149; One or more cue strings is missing its time or is blank<br />";
        }
        if (isOutOfRange) {
            errMsg += "&#149; One or more cue strings exceeds the current duration<br />";
        }
        if (isInvalid) {
            errMsg += "&#149; Cue strings cannot contain double quotes or commas within parentheses<br />";
        }
        
        // stop and alert if errors
        if (errMsg != '') {
            msgNode.innerHTML = errMsg;
            msgNode.style.color = "Red";
            msgNode.style.display = "block";
            return false;
        } 
        
        // provide options for save
        var eventObj = xml.getElementsByTagName('EVENT')[0];
        var id = eventObj.getAttribute('ID');
        if ( (!eventEditorDurationUpdated) && (id == -1) ) {
            showSaveNewEvent(longestDurationStr);
            return false;
        }
            
    } else if (activeEditor.systemLevel == 1) { // validate package
        // initialize
        xml = packageRequest.responseXML;
        msgNode = $('packageEditor_Messages');
        // clear message node
        msgNode.style.display = "none";
        msgNode.style.color = "Red";
        msgNode.innerHTML = "";
        
        // check required fields
        if ($('packageEditor_Name').value.strip() == '') 
            errMsg += "&#149; Package name is a required field<br />";
        if ($('packageEditor_Duration').value.strip() == '') 
            errMsg += "&#149; Package duration is a required field<br />";
        
        // stop and alert if errors
        if (errMsg != '') {
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }

        // get id to see if this is an update
        var packageObj = xml.getElementsByTagName('PACKAGE')[0];
        var packageId = packageObj.getAttribute('ID');
        
        // check if name is unique
        if (!checkUniqueName(packageId, $('packageEditor_Name').value.strip(), 1)) {
            errMsg += "&#149; An event with this name already exists<br />";
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        }
        
        // get longest list duration
        var durationStr = padDurationStr($('packageEditor_Duration').value.strip());
        var longestDurationStr = getLongestDuration();
        
        // check duration       
        if (longestDurationStr > durationStr) {
            errMsg += "&#149; The package list exceeds its duration<br />";
            msgNode.innerHTML = errMsg;
            msgNode.style.display = "block";
            return false;
        } 
        
        // validate static fields  
        // duration
        if (!($('packageEditor_Duration').value.strip().match(durationRegex)))
            errMsg += "&#149; Package duration is not formatted correctly<br />";
        // air dates
        if (($('packageEditor_AirDateFrom').value.strip() != '') && !($('packageEditor_AirDateFrom').value.strip().match(dateRegex)))
            errMsg += "&#149; Air date start is not formatted correctly<br />";
        if (($('packageEditor_AirDateTo').value.strip() != '') && !($('packageEditor_AirDateTo').value.strip().match(dateRegex)))
            errMsg += "&#149; Air date end is not formatted correctly<br />";
            
        // cue strings
        if (($('packageEditor_CueStringStart').value.strip() != '') && ($('packageEditor_CueStringStart').value.match(invalidCueStrRegex)))
            errMsg += "&#149; Cue string start cannot contain double quotes or commas within parentheses<br />";
        if (($('packageEditor_CueStringEnd').value.strip() != '') && ($('packageEditor_CueStringEnd').value.match(invalidCueStrRegex)))
            errMsg += "&#149; Cue string end cannot contain double quotes or commas within parentheses<br />";
                    
        // validate metadata fields
        errMsg += validateMDFields(xml, msgNode);
        
        // validate cue strings
        var durationStr = padDurationStr($('packageEditor_Duration').value.strip());
        var cues = $('packageEditorCues').immediateDescendants();
        var isIncomplete = false;
        var isOutOfRange = false;
        var isInvalid = false;
        for (var i=0, len=cues.length; i<len; i++) {
            var time = cues[i].getElementsBySelector('input[type="text"]')[0];
            var cueString = cues[i].getElementsBySelector('input[type="text"]')[1];
            if (time && cueString) {
                if ( ( (cueString.value.strip() == '') && (time.value.strip() != '') )
                        || ( (cueString.value.strip() != '') && (time.value.strip() == '') ) ) {
                    isIncomplete = true;
                }
                if (time.value.strip() != '') {
                    var timeValue = padDurationStr(time.value.strip());
                    if (timeValue > durationStr) isOutOfRange = true;
                }
                if (cueString.value.match(invalidCueStrRegex)) isInvalid = true;
            }
        }
        if (isIncomplete) {
            errMsg += "&#149; One or more cue strings is missing its time or is blank<br />";
        }
        if (isOutOfRange) {
            errMsg += "&#149; One or more cue strings exceeds the current duration<br />";
        }
        if (isInvalid) {
            errMsg += "&#149; Cue strings cannot contain double quotes or commas within parentheses<br />";
        }
    } 
   
    // stop and alert if errors
    if (errMsg != '') {
        msgNode.innerHTML = errMsg;
        msgNode.style.color = "Red";
        msgNode.style.display = "block";
        return false;
    } 
    
    //alert('successful validation');
    return true;
}

// function to get longest duration string in event editor
function getLongestDuration() {
    var durationElStr = activeEditorPageId + "_Duration";
    var durationStr = (activeEditorPageId == 'multiPackage') ? "00:30:00" : padDurationStr($(durationElStr).value.strip());
    
    // get longest list duration
    var longestDuration = [0,0,0,0,0,0];
    for (var i=0, len=activeEditor.ddLists.length; i<len; i++) {
        var listEls = $(activeEditor.ddLists[i].tagId).immediateDescendants();
        var cumTime = [0,0,0,0,0,0];
        for (var j=0, jlen=listEls.length; j<jlen; j++) {
            var peca = activeEditor.getPeca(listEls[j]);
            cumTime = activeEditor.ddLists[i].addTime(cumTime, peca.duration);
        }
        // compare cumTime to longest
        longestDuration = returnLargerDuration(cumTime, longestDuration);
    }
    var longestDurationStr = parseInt(longestDuration[3],10).toPaddedString(2,10) + ":" + parseInt(longestDuration[4],10).toPaddedString(2,10) + ":" + parseInt(longestDuration[5],10).toPaddedString(2,10);
    
    return longestDurationStr;
}

// function to show save new event popup
function showSaveNewEvent (longestDurStr) {
    var durList = $('saveNewEventDuration');
    // clear out list
    var options = durList.immediateDescendants();
    for (var i=0, len=options.length; i<len; i++) {
        options[i].remove();
    }
   
    // locate index of longest duration
    var startIndex = 0;
    for (var i=0, len=activeEditor.timeSlots.length; i<len; i++) {
        if (longestDurStr == padDurationStr(activeEditor.timeSlots[i])) {
            startIndex = i;
            break;
        }
    }
    // populate duration select
    for (var i=startIndex, len=activeEditor.timeSlots.length; i<len; i++) {
        // check that duration option is an increment of 15 seconds
        var durStr = padDurationStr(activeEditor.timeSlots[i]);
        var durSplit = durStr.split(':');
        var totalSeconds = (parseInt(durSplit[0],10) * 3600) + (parseInt(durSplit[1],10) * 60) + parseInt(durSplit[2],10);
        if ( (totalSeconds % 15) == 0 ) {
            var optionEl = document.createElement('option');
            optionEl.value = activeEditor.timeSlots[i];
            optionEl.text = activeEditor.timeSlots[i];
            durList.options.add(optionEl);
        }
    }
    // add final option because it's not in time slots list
    var optionEl = document.createElement('option');
    optionEl.value = "30:00";
    optionEl.text = "30:00";
    durList.options.add(optionEl);    

    // display popup
    $('saveNewEventPopup').style.display = "block";
    coverPageForAlert($('saveNewEventPopup'));
}

function hideSaveNewEvent() {
    uncoverPageForAlert();
    $('saveNewEventPopup').style.display = "none";
}

function saveNewEvent() {
    // assign new duration to event
    var durList = $('saveNewEventDuration');
    var duration = durList.options[durList.selectedIndex].value;
    $('eventEditor_Duration').value = duration;
    
    eventEditorDurationUpdated = true;
    // save event
    saveEditorObject();
}

// function to return the larger of two duration arrays
function returnLargerDuration(durA, durB) {
    // ignore first three fields (year, month, day)
    if ( (parseInt(durA[3],10) == parseInt(durB[3],10)) &&
            (parseInt(durA[4],10) == parseInt(durB[4],10)) ) {
        if (parseInt(durA[5],10) == parseInt(durB[5],10)) {
            return durA; // they are the same
        } else {
            return (parseInt(durA[5],10) > parseInt(durB[5],10)) ? durA : durB;
        }
    }
    
    if (parseInt(durA[3],10) == parseInt(durB[3],10)) {
        if (parseInt(durA[4],10) == parseInt(durB[4],10)) {
            return durA; // they are the same
        } else {
            return (parseInt(durA[4],10) > parseInt(durB[4],10)) ? durA : durB;
        }
    }
    
    if (parseInt(durA[3],10) == parseInt(durB[3],10)) {
        return durA; // they are the same
    } else {
        return (parseInt(durA[3],10) > parseInt(durB[3],10)) ? durA : durB;
    }
}

function validateMDFields(xml, msgNode) {
    // validate metadata fields  
    var errMsg = "";
    var mdFields = xml.getElementsByTagName('METADATAFIELD');
    for (var i=0, len=mdFields.length; i<len; i++) {
        var mdId = mdFields[i].getAttribute('ID');
        var mdType = mdFields[i].getAttribute('Type');
        var mdName = mdFields[i].getAttribute('Name');
        var fieldId = "metadatafieldid_" + mdId + "_type_" + mdType;
        var field = $(fieldId);
        if (mdType == 'int') {
            if (field.value.strip() && !field.value.strip().match(intRegex))
                errMsg += "&#149; " + mdName + " is not formatted correctly<br />";
        } else if (mdType == 'decimal') {
            if (field.value.strip() && !field.value.strip().match(decimalRegex))
                errMsg += "&#149; " + mdName + " is not formatted correctly<br />";
        } else if (mdType == 'date') {
            if (field.value.strip() && !field.value.strip().match(dateRegex))
                errMsg += "&#149; " + mdName + " is not formatted correctly<br />";
        } else if (mdType == 'time') {
            if (field.value.strip() && !field.value.strip().match(timeRegex))
                errMsg += "&#149; " + mdName + " is not formatted correctly<br />";
        } 
    }
    return errMsg;
}

// function to write out metadata save xml
function writeMDXML (metaDataFields, id) {
    var sessionIdBLStr = "SessionID=\"" + sessionId + "\" ";
    // get metadata values
    var xmlStr = "";
    for (var i=0, len=metaDataFields.length; i<len; i++) {
        var mdSplit = metaDataFields[i].id.split('_');
        var mdId = mdSplit[1];
        var mdType = mdSplit[3];
        if ( (mdType != 'list') && (metaDataFields[i].value.strip() != '') ) {
            xmlStr += "<BL_METADATAVALUE BLID=\"\" ElementID=\"" + id + 
                    "\" MDFieldID=\"" + mdId + "\" " + sessionIdBLStr;
            if (mdType == 'int') {
                xmlStr += "ValueInt=\"" + metaDataFields[i].value.strip() + "\" />";
            } else if (mdType == 'decimal') {
                xmlStr += "ValueDecimal=\"" + metaDataFields[i].value.strip() + "\" />";
            } else if (mdType == 'varchar100') {
                xmlStr += "ValueVarchar100=\"" + metaDataFields[i].value.strip() + "\" />";
            } else if (mdType == 'varchar1000') {
                xmlStr += "ValueVarchar1000=\"" + metaDataFields[i].value.strip() + "\" />";
            //} else if (mdType == 'datetime') {
            //    xmlStr += "ValueDateTime=\"" + ConvertToXMLDate(metaDataFields[i].value.strip()) + "\" />";
            } else if (mdType == 'date') {
                xmlStr += "ValueDateTime=\"" + ConvertToXMLDate(metaDataFields[i].value.strip()) + "\" />";
            } else if (mdType == 'time') {
                xmlStr += "ValueDateTime=\"" + ConvertToXMLDate(metaDataFields[i].value.strip()) + "\" />";
            }
        } else if (mdType == 'list') {
            if (metaDataFields[i].selectedIndex >= 0) {
                xmlStr += "<BL_METADATAVALUE BLID=\"\" ElementID=\"" + id + 
                        "\" MDFieldID=\"" + mdId + "\" " + sessionIdBLStr;
                xmlStr += "ValueMDID=\"" + parseInt(metaDataFields[i].options[metaDataFields[i].selectedIndex].value,10) + "\" />";
            } else {
                xmlStr += "<BL_METADATAVALUE BLID=\"\" ElementID=\"" + id + 
                    "\" MDFieldID=\"" + mdId + "\" " + sessionIdBLStr + "/>";
            }
        } else {
            xmlStr += "<BL_METADATAVALUE BLID=\"\" ElementID=\"" + id + 
                    "\" MDFieldID=\"" + mdId + "\" " + sessionIdBLStr + "/>";
        }
    }
    return xmlStr;
}

// function to clear search results
function clearSearchResults() {
    // disable add button
    var resultsAddBtn = activeEditorPageId + "Add";
    if ($(resultsAddBtn)) $(resultsAddBtn).setAttribute('disabled','disabled');

    // clear select box
    var resultsId = "";
    if (activeEditorPageId != 'liveControl') {
        resultsId = activeEditorPageId + "Results";
    } else {
        resultsId = (searchChoice == 'Package') ? "liveControlPackageResults" : "liveControlEventResults";
    }
    var resultsBox = $(resultsId);
    var options = resultsBox.immediateDescendants();
    for (var i=0, len=options.length; i<len; i++) {
        options[i].remove();
    }
    
    // disable sort dropdowns
    if (activeEditorPageId == 'liveControl') {
        $('liveControlPackageSort').setAttribute('disabled', 'disabled');
        $('liveControlEventSort').setAttribute('disabled', 'disabled');
    } else if (activeEditorPageId == 'multiPackage') {
        $('multiPackageSort').setAttribute('disabled', 'disabled');
    } else if (activeEditorPageId == 'scheduleEditor') {
        $('scheduleEditorSort').setAttribute('disabled', 'disabled');
    } else if (activeEditorPageId == 'packageEditor') {
        $('packageEditorSort').setAttribute('disabled', 'disabled');
    } else if (activeEditorPageId == 'eventEditor') {
        $('eventEditorSort').setAttribute('disabled', 'disabled');
    } else if (activeEditorPageId == 'comboEditor') {
        $('comboEditorSort').setAttribute('disabled', 'disabled');
    }
}

// event handler for index change on search results
function resultsIndexChanged(listBox) {
    if (activeEditor.systemLevel < 4) {  // all levels except asset
        // update icon
        activeEditor.updateIcon(listBox.options[listBox.selectedIndex].value);
        // enable add button
        var resultsAddBtn = activeEditorPageId + "Add";
        $(resultsAddBtn).removeAttribute('disabled');
        
        // special code to change event editor color if all lists are empty
        if (activeEditor.systemLevel == 2) {
            // only if all lists are empty then update color on selection
            var isEmpty = true;
            for (var i=0, len=activeEditor.ddLists.length; i<len; i++) {
                if ($(activeEditor.ddLists[i].tagId).immediateDescendants().length > 0) {
                    isEmpty = false;
                    break;
                }
            }
            
            // update color of is empty
            if (isEmpty) {
                $('eventEditor_Color').style.backgroundColor = activeEditor.dragContainer.firstDescendant().style.backgroundColor;
            }
        }
    } else { // handle selected index change on asset
        if (listBox.selectedIndex > -1) {
            $('assetEditor_AddBtn1').removeAttribute('disabled');
            $('assetEditor_AddBtn2').removeAttribute('disabled');
            updateMediaInfo();
        } else {
            $('assetEditor_AddBtn1').setAttribute('disabled', 'disabled');
            $('assetEditor_AddBtn2').setAttribute('disabled', 'disabled');
        }
    }
}

// updates media info on asset editor
function updateMediaInfo () {
    var media = searchRequest.responseXML.getElementsByTagName('MEDIA');
    var listBox = $('assetEditorResults');
    var selectedId = listBox.options[listBox.selectedIndex].value
    var selectedMedia = null;
    // get selected media
    for (var i=0, len=media.length; i<len; i++) {
        if (selectedId == media[i].getAttribute('ID')) {
            selectedMedia = media[i];
            break;
        }
    }
    // update panel with selected media info
    var container = $('assetEditor_MediaInfo');
    // clear any previous info
    var infoEls = container.immediateDescendants();
    for (var i=0, len=infoEls.length; i<len; i++) {
        infoEls[i].remove();
    }
    // add new info
    var mediaId = selectedMedia.getAttribute('ID');
    var sourcePath = selectedMedia.getAttribute('SourcePath');
    var fileCount = selectedMedia.getAttribute('FileCount');
    var ingestedDate = selectedMedia.getAttribute('CreatedOn');
    var isImageSet = selectedMedia.getAttribute('IsImageSet');
    var ingestedPath = selectedMedia.getAttribute('IngestedFromPath');
    var thumbVidPath = selectedMedia.getAttribute('ThumbnailVidPath'); // possible null
    var thumbJpgPath = selectedMedia.getAttribute('ThumbnailJPEG'); // possible null
    
    var info1 = document.createElement('div');
    info1.style.overflow = "hidden";
    info1.innerHTML = "<span style='font-weight:bold'>ID: </span><span>" + mediaId + "</span>";
    var info2 = document.createElement('div');
    info2.style.overflow = "hidden";
    // display files or duration based on rules
    if (sourcePath.strip().search(/M_/i) == 0) {
        if (isImageSet == 1) {
            info2.innerHTML = "<span style='font-weight:bold'>Image Files: </span><span>" + fileCount + "</span>";
        } else {
            var totalSeconds = Math.round(parseInt(fileCount,10)/60);
            var minutes = Math.floor(totalSeconds/60);
            var seconds = totalSeconds % 60;
            var duration = minutes.toPaddedString(2,10) + ":" + seconds.toPaddedString(2,10);
            info2.innerHTML = "<span style='font-weight:bold'>Duration: </span><span>" + duration + "</span>";
        }
    } else if (sourcePath.strip().search(/R_|T_/i) == 0) {
        if (isImageSet == 1) {
            info2.innerHTML = "<span style='font-weight:bold'>Image Files: </span><span>" + fileCount + "</span>";
        } else {
            var totalSeconds = Math.round(parseInt(fileCount,10)/30);
            var minutes = Math.floor(totalSeconds/60);
            var seconds = totalSeconds % 60;
            var duration = minutes.toPaddedString(2,10) + ":" + seconds.toPaddedString(2,10);
            info2.innerHTML = "<span style='font-weight:bold'>Duration: </span><span>" + duration + "</span>";
        }
    } else {
        info2.innerHTML = "<span style='font-weight:bold'>Image Files: </span><span>" + fileCount + "</span>";
    }
    var info2a = document.createElement('div');
    info2a.style.overflow = "hidden";
    info2a.innerHTML = "<span style='font-weight:bold'>Ingested On: </span><span>";
    if (ingestedDate)
        info2a.innerHTML += "<span>" + ingestedDate + "</span>";
    var info3 = document.createElement('div');
    info3.style.overflow = "hidden";
    info3.innerHTML = "<span style='font-weight:bold'>Source Path: </span><br /><span>" + sourcePath + "</span>";
    var info4 = document.createElement('div');
    info4.style.overflow = "hidden";
    info4.innerHTML = "<span style='font-weight:bold'>Ingested From Path: </span><br /><span>" + ingestedPath + "</span>";
    var info5 = document.createElement('div');
    info5.style.overflow = "hidden";
    info5.innerHTML = "<span style='font-weight:bold'>Thumbnail Vid Path: </span>";
    if (thumbVidPath)
        info5.innerHTML += "<span>" + thumbVidPath + "</span>";
    var info6 = document.createElement('div');
    info6.style.overflow = "hidden";
    info6.innerHTML = "<span style='font-weight:bold'>Thumbnail JPEG: </span><span>";
    if (thumbJpgPath)
        info6.innerHTML += "<span>" + thumbJpgPath + "</span>";
    container.appendChild(info1);
    container.appendChild(info2);
    container.appendChild(info2a);
    container.appendChild(info3);
    container.appendChild(info4);
    container.appendChild(info5);
    container.appendChild(info6);
}

var searchRequest = null;

function scrubSearchValues () {
    var fields = sfXML.getElementsByTagName('Field');
    for (var i=0, len=fields.length; i<len; i++) {
        var fieldValue = fields[i].getAttribute('Value');
        if (fieldValue && fieldValue.search(/'/) >= 0) {
            fields[i].removeAttribute('Value');
            var newValue = fieldValue.replace(/'/g,"''''");
            fields[i].setAttribute('Value', newValue);
        }
    }
}

function getSearchResults() {
    searchRequest = new XMLHttpRequest();
    
    // clear any search alerts
    if (activeEditorPageId != 'liveControl') {
        var alertStr = activeEditorPageId + "_SearchAlerts";
        var alertNode = $(alertStr);
        alertNode.style.display = "none";
    } else if (activeEditorPageId == 'liveControl') {
        var alertStr1 = activeEditorPageId + "_SearchPackageAlerts";
        var alertStr2 = activeEditorPageId + "_SearchEventAlerts";
        var alertNode = $(alertStr1);
        alertNode.style.display = "none";
        alertNode = $(alertStr2);
        alertNode.style.display = "none";
    }
    
    // first clear search results
    clearSearchResults();
    
    if (activeEditorPageId != 'assetEditor') {
        // add values to search xml 
        addSearchValuesToXML();  

        var url = "AjaxPost.aspx";
        searchRequest.open('POST', url, true);
        searchRequest.setRequestHeader("Content-Type", "text/xml");
        searchRequest.send(sfXML);
        searchRequest.onreadystatechange = processSearchStateChange;
    } else {
        // make request to db to get live control info
        //var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetMediaList\" />";
        var fileName = $('assetEditor_Search_Filename').value.strip();
        var dateStart = ConvertToXMLDate($('assetEditor_Search_FileCreationDateFrom').value.strip());
        var dateEnd = ConvertToXMLDate($('assetEditor_Search_FileCreationDateTo').value.strip());
        var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetListMedia\" FileName=\"" + escapeForXML(fileName) + "\" ";
        sProc += "DateStart=\"" + dateStart + "\" DateEnd=\"" + dateEnd + "\" />";
        callAjaxPost(searchRequest, sProc, processSearchMediaStateChange);
    }
    //$('pageContainer').addClassName('fadedBG');
    $('searchingMsg').style.display = "block";
}

// ajax state change handler
function processSearchStateChange () {
	if (searchRequest.readyState == 4) {
		if (searchRequest.status == 200) {
		    if (searchRequest.responseXML != null) {
		        loadSearchResults();
	        }
	        //$('pageContainer').removeClassName('fadedBG');
	        $('searchingMsg').style.display = "none";
		}
	} 
}

// ajax state change handler
function processSearchMediaStateChange () {
	if (searchRequest.readyState == 4) {
		if (searchRequest.status == 200) {
		    if (searchRequest.responseXML != null) {
		        var media = searchRequest.responseXML.getElementsByTagName('MEDIA');
                if (media.length == 0) {
                    var alertNode = $('assetEditor_SearchAlerts');
                    alertNode.innerHTML = "No results were found for the given search criteria.";
                    alertNode.style.color = "Green";
                    alertNode.style.fontWeight = "bold";
                    alertNode.style.display = "block";
                    $('searchingMsg').style.display = "none";
                    return;
                }
                var listBox = $('assetEditorResults');
                for (var i=0, len=media.length; i<len; i++) {
                    var optionEl = document.createElement('option');
                    optionEl.text = media[i].getAttribute('SourcePath');
                    optionEl.value = media[i].getAttribute('ID');
//                    var activityLog = media[i].getElementsByTagName('ACTIVITYLOG')[0];
                    optionEl.setAttribute('label',media[i].getAttribute('CreatedOn'));
                    listBox.options.add(optionEl);
                }
                var sortDrop = $('assetEditorSort');
                sortDrop.options[0].selected = true;
                sortDrop.removeAttribute('disabled');
		    }
		    //$('pageContainer').removeClassName('fadedBG');
	        $('searchingMsg').style.display = "none";
		}
	} 
}

function loadSearchResults () {
    var alertStr = activeEditorPageId + "_SearchAlerts";
    var alertNode = $(alertStr);
    // load options
    if (activeEditorPageId == 'scheduleEditor') {
        var packages = searchRequest.responseXML.getElementsByTagName('PACKAGE');
        if (packages.length == 0) {
            alertNode.innerHTML = "No results were found for the given search criteria.";
            alertNode.style.color = "Green";
            alertNode.style.fontWeight = "bold";
            alertNode.style.display = "block";
            return;
        }
        // default sort to Name and remove disabled
        var sortDrop = $('scheduleEditorSort');
        sortDrop.options[0].selected = true;
        sortDrop.removeAttribute('disabled');
        var listBox = $('scheduleEditorResults');
        for (var i=0, len=packages.length; i<len; i++) {
            var packagePeca = loadPackageFromXML(packages[i]);
            var optionEl = document.createElement('option');
            optionEl.text = packagePeca.name;
            optionEl.value = packagePeca.tagId;
            if (packagePeca.thisEnabled == false) optionEl.className = "disabledOption";
            var activityLog = packages[i].getElementsByTagName('ACTIVITYLOG')[0];
            optionEl.setAttribute('label',activityLog.getAttribute('CreatedOn'));
            listBox.options.add(optionEl);
        }
	} else if (activeEditorPageId == 'packageEditor') {
        var events = searchRequest.responseXML.getElementsByTagName('EVENT');
        if (events.length == 0) {
            alertNode.innerHTML = "No results were found for the given search criteria.";
            alertNode.style.color = "Green";
            alertNode.style.fontWeight = "bold";
            alertNode.style.display = "block";
            return;
        }
        // default sort to Name and remove disabled
        var sortDrop = $('packageEditorSort');
        sortDrop.options[0].selected = true;
        sortDrop.removeAttribute('disabled');
        var listBox = $('packageEditorResults');
        for (var i=0, len=events.length; i<len; i++) {
            var eventPeca = loadEventFromXML(events[i]);
            var optionEl = document.createElement('option');
            optionEl.text = eventPeca.name;
            optionEl.value = eventPeca.tagId;
            if (eventPeca.thisEnabled == false) optionEl.className = "disabledOption";
            var activityLog = events[i].getElementsByTagName('ACTIVITYLOG')[0];
            optionEl.setAttribute('label',activityLog.getAttribute('CreatedOn'));
            listBox.options.add(optionEl);
        }
	} else if (activeEditorPageId == 'multiPackage') {
        var events = searchRequest.responseXML.getElementsByTagName('EVENT');
        if (events.length == 0) {
            alertNode.innerHTML = "No results were found for the given search criteria.";
            alertNode.style.color = "Green";
            alertNode.style.fontWeight = "bold";
            alertNode.style.display = "block";
            return;
        }
        // default sort to Name and remove disabled
        var sortDrop = $('multiPackageSort');
        sortDrop.options[0].selected = true;
        sortDrop.removeAttribute('disabled');
        var listBox = $('multiPackageResults');
        for (var i=0, len=events.length; i<len; i++) {
            var eventPeca = loadEventFromXML(events[i]);
            var optionEl = document.createElement('option');
            optionEl.text = eventPeca.name;
            optionEl.value = eventPeca.tagId;
            if (eventPeca.thisEnabled == false) optionEl.className = "disabledOption";
            var activityLog = events[i].getElementsByTagName('ACTIVITYLOG')[0];
            optionEl.setAttribute('label',activityLog.getAttribute('CreatedOn'));
            listBox.options.add(optionEl);
        }
	} else if (activeEditorPageId == 'eventEditor') {
        var combos = searchRequest.responseXML.getElementsByTagName('ASSET');
        if (combos.length == 0) {
            alertNode.innerHTML = "No results were found for the given search criteria.";
            alertNode.style.color = "Green";
            alertNode.style.fontWeight = "bold";
            alertNode.style.display = "block";
            return;
        }
        // default sort to Name and remove disabled
        var sortDrop = $('eventEditorSort');
        sortDrop.options[0].selected = true;
        sortDrop.removeAttribute('disabled');
        var listBox = $('eventEditorResults');
        for (var i=0, len=combos.length; i<len; i++) {
            var comboPeca = loadComboFromXML(combos[i]);
            var optionEl = document.createElement('option');
            optionEl.text = comboPeca.name;
            optionEl.value = comboPeca.tagId;
            if (comboPeca.thisEnabled == false) optionEl.className = "disabledOption";
            var activityLog = combos[i].getElementsByTagName('ACTIVITYLOG')[0];
            optionEl.setAttribute('label',activityLog.getAttribute('CreatedOn'));
            listBox.options.add(optionEl);
        }
	} else if (activeEditorPageId == 'comboEditor') {
        var assets = searchRequest.responseXML.getElementsByTagName('ASSET');
        if (assets.length == 0) {
            alertNode.innerHTML = "No results were found for the given search criteria.";
            alertNode.style.color = "Green";
            alertNode.style.fontWeight = "bold";
            alertNode.style.display = "block";
            return;
        }
        // default sort to Name and remove disabled
        var sortDrop = $('comboEditorSort');
        sortDrop.options[0].selected = true;
        sortDrop.removeAttribute('disabled');
        var listBox = $('comboEditorResults');
        for (var i=0, len=assets.length; i<len; i++) {
            var assetPeca = loadAssetFromXML(assets[i]);
            var optionEl = document.createElement('option');
            optionEl.text = assetPeca.name;
            optionEl.value = assetPeca.tagId;
            if (assetPeca.thisEnabled == false) optionEl.className = "disabledOption";
            var activityLog = assets[i].getElementsByTagName('ACTIVITYLOG')[0];
            optionEl.setAttribute('label',activityLog.getAttribute('CreatedOn'));
            listBox.options.add(optionEl);
        }
	} else if (activeEditorPageId == 'assetEditor') {
	    // default sort to Name and remove disabled
        var sortDrop = $('assetEditorSort');
        sortDrop.options[0].selected = true;
        sortDrop.removeAttribute('disabled');
    } else if (activeEditorPageId == 'liveControl') {
        var resultsBox = (searchChoice == 'Package') ? $('liveControlPackageResultsBox') : $('liveControlEventResultsBox');
        resultsBox.removeClassName('collapsed');
        
        if (searchChoice == 'Package') {
            var packages = searchRequest.responseXML.getElementsByTagName('PACKAGE');
            if (packages.length == 0) {
                var alert = $('liveControl_SearchPackageAlerts');
                alert.innerHTML = "No results were found for the given search criteria.";
                alert.style.color = "Green";
                alert.style.fontWeight = "bold";
                alert.style.display = "block";
                return;
            }
            var listBox = $('liveControlPackageResults');
            for (var i=0, len=packages.length; i<len; i++) {
                //var packagePeca = loadPackageFromXML(packages[i]);
                var optionEl = document.createElement('option');
                optionEl.text = packages[i].getAttribute('Name');
                optionEl.value = packages[i].getAttribute('ID');
                if (packages[i].getAttribute('ThisEnabled') == '0') optionEl.className = "disabledOption";
                var activityLog = packages[i].getElementsByTagName('ACTIVITYLOG')[0];
                optionEl.setAttribute('label',activityLog.getAttribute('CreatedOn'));
                listBox.options.add(optionEl);
            }
        } else {
            var events = searchRequest.responseXML.getElementsByTagName('EVENT');
            if (events.length == 0) {
                var alert = $('liveControl_SearchEventAlerts');
                alert.innerHTML = "No results were found for the given search criteria.";
                alert.style.color = "Green";
                alert.style.fontWeight = "bold";
                alert.style.display = "block";
                return;
            }
            var listBox = $('liveControlEventResults');
            for (var i=0, len=events.length; i<len; i++) {
                var eventPeca = loadEventFromXML(events[i]);
                var optionEl = document.createElement('option');
                optionEl.text = eventPeca.name;
                optionEl.value = eventPeca.tagId;
                if (eventPeca.thisEnabled == false) optionEl.className = "disabledOption";
                var activityLog = events[i].getElementsByTagName('ACTIVITYLOG')[0];
                optionEl.setAttribute('label',activityLog.getAttribute('CreatedOn'));
                listBox.options.add(optionEl);
            }
        }
        // default sort to Name and remove disabled
        var sortDrop = (searchChoice == 'Package') ? $('liveControlPackageSort') : $('liveControlEventSort');
        sortDrop.options[0].selected = true;
        sortDrop.removeAttribute('disabled');
        
	} 
    searchRequest.abort();
}

// allows javascript array sort by number
function sortNumber(a,b)
{
    return a - b;
}

// function to sort results in editor
function sortResults(select, listBoxId) {
    //if (select.selectedIndex == 0) return;
    
    var listBox = $(listBoxId);
    
    if (select.options[select.selectedIndex].text == 'Name') { // sort by name
        var options = listBox.immediateDescendants();
        var optionNames = [];
        var optionNamesUpper = [];
        var optionNamesSorted = [];
        var optionValues = [];
        var optionCreatedDates = [];
        var optionClasses = [];
        // get values and destroy current options
        for (var i=0, len=options.length; i<len; i++) {
            optionNames[i] = options[i].text;
            optionNamesUpper[i] = options[i].text.toUpperCase();
            optionNamesSorted[i] = options[i].text.toUpperCase();
            optionValues[i] = options[i].value;
            optionCreatedDates[i] = options[i].getAttribute('label');
            optionClasses[i] = options[i].hasClassName('disabledOption');
            options[i].remove();
        }
        // sort array and add options back
        optionNamesSorted.sort();
        for (var i=0, len=optionNames.length; i<len; i++) {
            var optionEl = document.createElement('option');
            var index = optionNamesUpper.indexOf(optionNamesSorted[i]);
            optionEl.text = optionNames[index];
            optionEl.value = optionValues[index];
            optionEl.setAttribute('label',optionCreatedDates[index]);
            optionEl.className = (optionClasses[index]) ? "disabledOption" : "";
            listBox.options.add(optionEl);
        }
    } else if (select.options[select.selectedIndex].text == 'Newest') { // sort by id
        if (listBoxId == 'assetEditorResults' || listBoxId == 'liveControlPackageResults' ) {  // use value field to get id
            var options = listBox.immediateDescendants();
            var optionNames =[];
            var optionValues = [];
            var optionValuesSorted = [];
            var optionCreatedDates = [];
            var optionClasses = [];
            // get values and destroy current options
            for (var i=0, len=options.length; i<len; i++) {
                optionNames[i] = options[i].text;
                optionValues[i] = parseInt(options[i].value,10);
                optionValuesSorted[i] = parseInt(options[i].value,10);
                optionCreatedDates[i] = options[i].getAttribute('label');
                optionClasses[i] = options[i].hasClassName('disabledOption');
                options[i].remove();
            }
            // sort array and add options back
            optionValuesSorted.sort(sortNumber).reverse();
            for (var i=0, len=optionNames.length; i<len; i++) {
                var optionEl = document.createElement('option');
                optionEl.value = optionValuesSorted[i];
                var index = optionValues.indexOf(parseInt(optionEl.value,10));
                optionEl.text = optionNames[index];
                optionEl.setAttribute('label',optionCreatedDates[index]);
                optionEl.className = (optionClasses[index]) ? "disabledOption" : "";
                listBox.options.add(optionEl);
            }
        } else { // lookup peca property to get id
            var options = listBox.immediateDescendants();
            var optionNames =[];
            var optionValues = [];
            var optionIDs = [];
            var optionCreatedDates = [];
            var optionIDsSorted = [];
            var optionClasses = [];
            // get values and destroy current options
            for (var i=0, len=options.length; i<len; i++) {
                optionNames[i] = options[i].text;
                optionIDs[i] = parseInt(activeEditor.getPecaById(options[i].value).dbId,10);
                optionIDsSorted[i] = optionIDs[i];
                optionValues[i] = options[i].value;
                optionCreatedDates[i] = options[i].getAttribute('label');
                optionClasses[i] = options[i].hasClassName('disabledOption');
                options[i].remove();
            }
            // sort array and add options back
            optionIDsSorted.sort(sortNumber).reverse();
            for (var i=0, len=optionNames.length; i<len; i++) {
                var optionEl = document.createElement('option');
                var index = optionIDs.indexOf(optionIDsSorted[i]);
                optionEl.text = optionNames[index];
                optionEl.value = optionValues[index];
                optionEl.setAttribute('label',optionCreatedDates[index]);
                optionEl.className = (optionClasses[index]) ? "disabledOption" : "";
                listBox.options.add(optionEl);
            }
        }
    }
}

// loads an unscheduled package peca
function loadPackageFromXML (packageXML) {
	// load data into a peca object
    var dbId = packageXML.getAttribute('ID');
	var name = packageXML.getAttribute('Name');
	var duration = parseXMLDate(packageXML.getAttribute('Duration'));
	var systemId = packageXML.getAttribute('SystemID');
	var thisEnabled = packageXML.getAttribute('ThisEnabled');
	var thisDayPart = packageXML.getAttribute('ThisDayPart');
	var thisStartDate = parseXMLDate(packageXML.getAttribute('ThisStartDate'));
	var thisEndDate = parseXMLDate(packageXML.getAttribute('ThisEndDate'));
	var thisColor = packageXML.getAttribute('ThisColor');
	var enabledNN = packageXML.getAttribute('EnabledNN');
	var ingestedNN = packageXML.getAttribute('IngestedNN');
	var onPlayersNN = packageXML.getAttribute('OnPlayersNN');
	var dayPartNN = packageXML.getAttribute('DayPartNN');
	var startDateNN = parseXMLDate(packageXML.getAttribute('StartDateNN'));
	var endDateNN = parseXMLDate(packageXML.getAttribute('EndDateNN'));
	var htmlNN = packageXML.getAttribute('htmlNN');
	var percentBreakdownNN = packageXML.getAttribute('PercentBreakdownNN');
	var cueStringStart = packageXML.getAttribute('CueStringStart');
	var cueStringEnd = packageXML.getAttribute('CueStringEnd');			
	var openForEditUserId = packageXML.getAttribute('OpenForEditUserID');
	var openForEditDateTime = parseXMLDate(packageXML.getAttribute('OpenForEditDateTime'));
	var isWebControlPackage = packageXML.getAttribute('IsWebControlPackage')
	
	var packagePeca = new DraggablePeca();
	packagePeca.load(1, null, 0, dbId, name, duration, systemId, -1, '', false, -1, 
	                thisEnabled, thisDayPart, thisStartDate, thisEndDate, thisColor, enabledNN, 
	                dayPartNN, startDateNN, endDateNN, ingestedNN, onPlayersNN, '', htmlNN, percentBreakdownNN,
	                cueStringStart, cueStringEnd, openForEditUserId, openForEditDateTime, isWebControlPackage);
	if (activeEditor) activeEditor.draggablePecas.push(packagePeca);
	return packagePeca;
}

// loads an unscheduled event peca
function loadEventFromXML (eventXML) {
	// load data into a peca object
    var dbId = eventXML.getAttribute('ID');
    var name = eventXML.getAttribute('Name');
    var duration = parseXMLDate(eventXML.getAttribute('Duration'));
    var zoneId = eventXML.getAttribute('ZoneID');
    var thisEnabled = eventXML.getAttribute('ThisEnabled');
    var thisDayPart = eventXML.getAttribute('ThisDayPart');
    var thisStartDate = parseXMLDate(eventXML.getAttribute('ThisStartDate'));
    var thisEndDate = parseXMLDate(eventXML.getAttribute('ThisEndDate'));
    var thisColor = eventXML.getAttribute('ThisColor');
    var enabledNN = eventXML.getAttribute('EnabledNN');
    var dayPartNN = eventXML.getAttribute('DayPartNN');
    var startDateNN = parseXMLDate(eventXML.getAttribute('StartDateNN'));
    var endDateNN = parseXMLDate(eventXML.getAttribute('EndDateNN'));			
    var ingestedNN = eventXML.getAttribute('IngestedNN');
    var onPlayersNN = eventXML.getAttribute('OnPlayersNN');
    var htmlNN = eventXML.getAttribute('htmlNN');
    var cueStringStart = eventXML.getAttribute('CueStringStart');
    var cueStringEnd = eventXML.getAttribute('CueStringEnd');			
    var openForEditUserId = eventXML.getAttribute('OpenForEditUserID');
    var openForEditDateTime = parseXMLDate(eventXML.getAttribute('OpenForEditDateTime'));
	
	var eventPeca = new DraggablePeca();
	eventPeca.load(2, null, 1, dbId, name, duration, -1, zoneId, '', false, -1, 
                thisEnabled, thisDayPart, thisStartDate, thisEndDate, thisColor, enabledNN, 
                dayPartNN, startDateNN, endDateNN, ingestedNN, onPlayersNN, '', htmlNN, '',
                cueStringStart, cueStringEnd, openForEditUserId, openForEditDateTime, false);
	if (activeEditor) activeEditor.draggablePecas.push(eventPeca);
	return eventPeca;
}

// loads an unscheduled combo peca
function loadComboFromXML (comboXML) {
	// load data into a peca object
    var dbId = comboXML.getAttribute('ID');
    var name = comboXML.getAttribute('Name');
    var duration = parseXMLDate(comboXML.getAttribute('Duration'));
    var channelsNN = comboXML.getAttribute('ChannelsNN');
    var isCombo = comboXML.getAttribute('IsCombo');
    var textTemplateId = comboXML.getAttribute('TextTemplateID');
    var thisEnabled = comboXML.getAttribute('ThisEnabled');
    var thisDayPart = comboXML.getAttribute('ThisDayPart');
    var thisStartDate = parseXMLDate(comboXML.getAttribute('ThisStartDate'));
    var thisEndDate = parseXMLDate(comboXML.getAttribute('ThisEndDate'));
    var thisColor = comboXML.getAttribute('ThisColor');
    var enabledNN = comboXML.getAttribute('EnabledNN');
    var dayPartNN = comboXML.getAttribute('DayPartNN');
    var startDateNN = parseXMLDate(comboXML.getAttribute('StartDateNN'));
    var endDateNN = parseXMLDate(comboXML.getAttribute('EndDateNN'));			
    var ingestedNN = comboXML.getAttribute('IngestedNN');
    var onPlayersNN = comboXML.getAttribute('OnPlayersNN');
    var colorNN = comboXML.getAttribute('ColorNN');
    var htmlNN = comboXML.getAttribute('htmlNN');
    var cueStringStart = comboXML.getAttribute('CueStringStart');
    var cueStringEnd = comboXML.getAttribute('CueStringEnd');			
    var openForEditUserId = comboXML.getAttribute('OpenForEditUserID');
    var openForEditDateTime = parseXMLDate(comboXML.getAttribute('OpenForEditDateTime'));
	
	var itemType = (isCombo == '1') ? 3 : 4;
	
	var comboPeca = new DraggablePeca();
	comboPeca.load(itemType, null, 1, dbId, name, duration, -1, -1, channelsNN, 
                isCombo, textTemplateId, 
                thisEnabled, thisDayPart, thisStartDate, thisEndDate, thisColor, enabledNN, 
                dayPartNN, startDateNN, endDateNN, ingestedNN, onPlayersNN, colorNN, htmlNN, '',
                cueStringStart, cueStringEnd, openForEditUserId, openForEditDateTime, false);
	if (activeEditor) activeEditor.draggablePecas.push(comboPeca);
	return comboPeca;
}

// loads an unscheduled asset peca
function loadAssetFromXML (assetXML) {
	// load data into a peca object
    var dbId = assetXML.getAttribute('ID');
    var name = assetXML.getAttribute('Name');
    var duration = parseXMLDate(assetXML.getAttribute('Duration'));
    var channelsNN = assetXML.getAttribute('ChannelsNN');
    var isCombo = assetXML.getAttribute('IsCombo');
    var textTemplateId = assetXML.getAttribute('TextTemplateID');
    var thisEnabled = assetXML.getAttribute('ThisEnabled');
    var thisDayPart = assetXML.getAttribute('ThisDayPart');
    var thisStartDate = parseXMLDate(assetXML.getAttribute('ThisStartDate'));
    var thisEndDate = parseXMLDate(assetXML.getAttribute('ThisEndDate'));
    var thisColor = assetXML.getAttribute('ThisColor');
    var enabledNN = assetXML.getAttribute('EnabledNN');
    var dayPartNN = assetXML.getAttribute('DayPartNN');
    var startDateNN = parseXMLDate(assetXML.getAttribute('StartDateNN'));
    var endDateNN = parseXMLDate(assetXML.getAttribute('EndDateNN'));			
    var ingestedNN = assetXML.getAttribute('IngestedNN');
    var onPlayersNN = assetXML.getAttribute('OnPlayersNN');
    var colorNN = assetXML.getAttribute('ColorNN');
    var htmlNN = assetXML.getAttribute('htmlNN');
    var cueStringStart = assetXML.getAttribute('CueStringStart');
    var cueStringEnd = assetXML.getAttribute('CueStringEnd');			
    var openForEditUserId = assetXML.getAttribute('OpenForEditUserID');
    var openForEditDateTime = parseXMLDate(assetXML.getAttribute('OpenForEditDateTime'));
	
	var itemType = (isCombo == '1') ? 3 : 4;
	
	var assetPeca = new DraggablePeca();
	assetPeca.load(itemType, null, 0, dbId, name, duration, -1, -1, channelsNN, 
                isCombo, textTemplateId, 
                thisEnabled, thisDayPart, thisStartDate, thisEndDate, thisColor, enabledNN, 
                dayPartNN, startDateNN, endDateNN, ingestedNN, onPlayersNN, colorNN, htmlNN, '',
                cueStringStart, cueStringEnd, openForEditUserId, openForEditDateTime, false);
	if (activeEditor) activeEditor.draggablePecas.push(assetPeca);
	return assetPeca;
}

// function to render meta-data fields
function renderMetaData(xml) {
    // get fields
    var metaDataFields = xml.getElementsByTagName('METADATAFIELD');
    
    // get options
    var metaDataOptions = xml.getElementsByTagName('METADATAOPTION');
    
    // get submetadata fields
    var subMetaDataFields = xml.getElementsByTagName('SUBMETADATAFIELD');
    
    // pre-process submeta fields to add a type attribute
    for (var i=0, len=subMetaDataFields.length; i<len; i++ ) {
        var typeAtt = xml.createAttribute('Type');
        typeAtt.value = 'sublist';
        subMetaDataFields[i].setAttributeNode(typeAtt);
    }
    
    // get submetadata options
    var subMetaDataOptions = xml.getElementsByTagName('SUBMETADATAOPTION');
    
    // pre-process fields to add submetadata
    var allFields = [];
    for (var i=0, len=metaDataFields.length; i<len; i++) {
        if (metaDataFields[i].getAttribute('SubMDFieldID')) {
            allFields.push(getItemById(metaDataFields[i].getAttribute('SubMDFieldID'), subMetaDataFields));
        }
        allFields.push(metaDataFields[i]);
    }
    
    //var rowCount = 0;
    var rows = [];
    var cols = [];
    var labels = [];
    var fields = [];
    var rowIndex = 0;
    
    for (var i=0, len=allFields.length; i<len; i++) {

        var col = document.createElement('col');
        col.className = "col widthM";
        cols[i%3] = (col);
        
        var fieldName = allFields[i].getAttribute('Name');
        var fieldLabel = document.createElement('label');
        fieldLabel.innerHTML = fieldName;
        labels[i%3] = (fieldLabel);
        
        var fieldType = allFields[i].getAttribute('Type');
        
        var field = null;
        if (fieldType == 'int') {
            field = document.createElement('input');
            field.setAttribute('type','text');
            field.setAttribute('onchange','setPageModified(true);');
            field.className = "widthM";
        } else if (fieldType == 'decimal') {
            field = document.createElement('input');
            field.setAttribute('type','text');
            field.setAttribute('onchange','setPageModified(true);');
            field.className = "widthM";
        } else if (fieldType == 'varchar100') {
            field = document.createElement('input');
            field.setAttribute('type','text');
            field.setAttribute('onchange','setPageModified(true);');
            field.className = "widthM";
        } else if (fieldType == 'varchar1000') {
            field = document.createElement('textarea');
            field.className = "widthM heightS";
            field.setAttribute('onchange','setPageModified(true);');
        } else if (fieldType == 'date') {
            field = document.createElement('input');
            field.setAttribute('type','text');
            field.setAttribute('onchange','setPageModified(true);');
            field.setAttribute('onfocus','this.select();lcs(this);');
            field.setAttribute('onclick','event.cancelBubble=true;this.select();lcs(this);');
            field.className = "date";
        } else if (fieldType == 'time') {
            field = document.createElement('input');
            field.setAttribute('type','text');
            field.setAttribute('onchange','setPageModified(true);');
            field.className = "time";
        } else if (fieldType == 'list') {
            field = document.createElement('select');
            field.setAttribute('onchange', 'updateSubMDOption(this); updateClientColor(this); setPageModified(true);');
            var options = [];
            for (var j=0, jlen=metaDataOptions.length; j<jlen; j++) {
                if (allFields[i].getAttribute('ID') ==  metaDataOptions[j].getAttribute('MDFieldID')) {
                    options.push(metaDataOptions[j]);
                }
            }
            // create default option
            var optionEl = document.createElement('option');
            optionEl.value = "-1";
            optionEl.text = "Select...";
            field.options.add(optionEl);
            for (var j=0, jlen=options.length; j<jlen; j++) {
                var optionEl = document.createElement('option');
                optionEl.value = options[j].getAttribute('ID');
                optionEl.text = options[j].getAttribute('Value');
                field.options.add(optionEl);
            }
        } else if (fieldType == 'sublist') {  // create submetadata field
            field = document.createElement('select');
            field.setAttribute('onchange', 'updateMDOptions(this); setPageModified(true);');
            var options = [];
            for (var j=0, jlen=subMetaDataOptions.length; j<jlen; j++) {
                if (allFields[i].getAttribute('ID') ==  subMetaDataOptions[j].getAttribute('SubMDFieldID')) {
                    options.push(subMetaDataOptions[j]);
                }
            }
            // create default option
            var optionEl = document.createElement('option');
            optionEl.value = "-1";
            optionEl.text = "Select...";
            field.options.add(optionEl);
            for (var j=0, jlen=options.length; j<jlen; j++) {
                var optionEl = document.createElement('option');
                optionEl.value = options[j].getAttribute('ID');
                optionEl.text = options[j].getAttribute('Value');
                field.options.add(optionEl);
            }
        }

        if (fieldType != 'sublist') {
            field.addClassName('metadata');
            field.id = "metadatafieldid_" + allFields[i].getAttribute('ID') + "_type_" + allFields[i].getAttribute('Type');
            fieldLabel.id = "metadatafieldlabelid_" + allFields[i].getAttribute('ID') + "_type_" + allFields[i].getAttribute('Type');
        } else {
            field.addClassName('submetadata');
            field.id = "submetadatafieldid_" + allFields[i].getAttribute('ID') + "_type_" + allFields[i].getAttribute('Type');
            fieldLabel.id = "submetadatafieldlabelid_" + allFields[i].getAttribute('ID') + "_type_" + allFields[i].getAttribute('Type');
        }
        
        fields[i%3] = field;
        
        
        cols[i%3].appendChild(labels[i%3]);
        cols[i%3].appendChild(fields[i%3]);
        
        if ( ( (i%3) == 2 ) || ( i == (len-1) ) ) {
            rows[rowIndex] = document.createElement('div');
            rows[rowIndex].className = "row";
            if (cols[0]) {
                rows[rowIndex].appendChild(cols[0]);
                var spacerXL = document.createElement('div');
                spacerXL.className = "spacerXL";
                rows[rowIndex].appendChild(spacerXL);
                cols[0] = null;
            }
            if (cols[1]) {
                rows[rowIndex].appendChild(cols[1]);
                var spacerXL = document.createElement('div');
                spacerXL.className = "spacerXL";
                rows[rowIndex].appendChild(spacerXL);
                cols[1] = null;
            }
            if (cols[2]) {
                rows[rowIndex].appendChild(cols[2]);
                var spacerXL = document.createElement('div');
                spacerXL.className = "spacerXL";
                rows[rowIndex].appendChild(spacerXL);
                cols[2] = null;
            }
            rowIndex++;
        }
    }
    
    for (var i=0; i<rowIndex; i++) {
        if (activeEditor.systemLevel == 4) $('assetEditorMetaData').appendChild(rows[i]);
        if (activeEditor.systemLevel == 3) $('comboEditorMetaData').appendChild(rows[i]);
        if (activeEditor.systemLevel == 2) $('eventEditorMetaData').appendChild(rows[i]);
        if (activeEditor.systemLevel == 1) $('packageEditorMetaData').appendChild(rows[i]);
    }
    
}

// function to load metadata values
function loadMDValues(xml, metaDataTag) {

    var mdFields = $(metaDataTag).getElementsByClassName('metadata');
    var metaDataValues = xml.getElementsByTagName('METADATAVALUE');
    
    for (var i=0, len=mdFields.length; i<len; i++) {
        var mdFieldSplit = mdFields[i].id.split('_');
        for (var j=0, jlen=metaDataValues.length; j<jlen; j++) {
            if (mdFieldSplit[1] == metaDataValues[j].getAttribute('MDFieldID')) {
                if (mdFieldSplit[3] == 'int') mdFields[i].value = metaDataValues[j].getAttribute('ValueInt');
                if (mdFieldSplit[3] == 'decimal') mdFields[i].value = metaDataValues[j].getAttribute('ValueDecimal');
                if (mdFieldSplit[3] == 'varchar100') mdFields[i].value = metaDataValues[j].getAttribute('ValueVarchar100');
                if (mdFieldSplit[3] == 'varchar1000') mdFields[i].value = metaDataValues[j].getAttribute('ValueVarchar1000');
                if (mdFieldSplit[3] == 'date') {
                    var date = parseXMLDate(metaDataValues[j].getAttribute('ValueDateTime'));
                    if (date) mdFields[i].value = date[1] + "/" + date[2] + "/" + date[0];
                }
                if (mdFieldSplit[3] == 'time') {
                    var time = parseXMLDate(metaDataValues[j].getAttribute('ValueDateTime'));
                    if (time) mdFields[i].value = time[4] + ":" + time[5];
                }
                if (mdFieldSplit[3] == 'list') {
                    var optionValue = metaDataValues[j].getAttribute('ValueMDID');
                    for (var k=0, klen=mdFields[i].options.length; k<klen; k++) {
                        if (mdFields[i].options[k].value == optionValue) {
                            mdFields[i].options[k].selected = true;
                        } else {
                            mdFields[i].options[k].selected = false;
                        }
                    }
                    updateSubMDOption(mdFields[i]);
                }
            }
        }          
    }
}

// function to filter metadata submetadata lists
function updateMDOptions (element) {

    var xml = null;    
    if (activeEditor.systemLevel == 4) xml = assetRequest.responseXML;
    if (activeEditor.systemLevel == 3) xml = comboRequest.responseXML;
    if (activeEditor.systemLevel == 2) xml = eventRequest.responseXML;
    if (activeEditor.systemLevel == 1) xml = packageRequest.responseXML;
    
    // get id for submetadata field selection
    var subMDOptionId = element.options[element.selectedIndex].value;
    
    // get metadataoptions from xml
    var metaDataOptions = xml.getElementsByTagName('METADATAOPTION');
    var metaDataFields = xml.getElementsByTagName('METADATAFIELD');

    // get mdField
    var subMDFieldId = element.id.split('_')[1];
    var mdFields = [];
    for (var i=0, len=metaDataFields.length; i<len; i++)
    {
        if (metaDataFields[i].getAttribute('SubMDFieldID') == subMDFieldId) {
            mdFields.push(metaDataFields[i]);
        }
    }    
    
    var mdFieldId = mdFields[0].getAttribute('ID');
    
    // get all metadata options for this metadata field
    var allOptions = [];
    for (var i=0, len=metaDataOptions.length; i<len; i++)
    {
        if (metaDataOptions[i].getAttribute('MDFieldID') == mdFieldId) {
            allOptions.push(metaDataOptions[i]);
        }
    }
    
    // get metadata options that match submetadata field selection
    var filteredOptions = [];
    for (var i=0, len=metaDataOptions.length; i<len; i++)
    {
        if (metaDataOptions[i].getAttribute('SubMDValueID') == subMDOptionId) {
            filteredOptions.push(metaDataOptions[i]);
        }
    }
    
    // update the metadata options with the filtered options
    var mdFieldStr = "metadatafieldid_" + mdFieldId + "_type_list";
    var mdField = $(mdFieldStr);
    // clear list
    for (var i=(mdField.options.length-1); i>=0; i--) {
        mdField.remove(i);
    }
    
    if (subMDOptionId == '-1') {
        // create default option
        var optionEl = document.createElement('option');
        optionEl.value = "-1";
        optionEl.text = "Select...";
        mdField.options.add(optionEl);
        // add all items
        for (var i=0, len=allOptions.length; i<len; i++) {
            var optionEl = document.createElement('option');
            optionEl.value = allOptions[i].getAttribute('ID');
            optionEl.text = allOptions[i].getAttribute('Value');
            mdField.options.add(optionEl);   
        }
    } else if (filteredOptions.length > 0) {
        // add new items
        for (var i=0, len=filteredOptions.length; i<len; i++) {
            var optionEl = document.createElement('option');
            optionEl.value = filteredOptions[i].getAttribute('ID');
            optionEl.text = filteredOptions[i].getAttribute('Value');
            mdField.options.add(optionEl);   
        }
        updateClientColor(mdField);
    }   

}

// function to update subMD option
function updateSubMDOption (element) {

    var xml = null;    
    if (activeEditor.systemLevel == 4) xml = assetRequest.responseXML;
    if (activeEditor.systemLevel == 3) xml = comboRequest.responseXML;
    if (activeEditor.systemLevel == 2) xml = eventRequest.responseXML;
    if (activeEditor.systemLevel == 1) xml = packageRequest.responseXML;

    // get id for metadata field selection
    var mdOptionId = element.options[element.selectedIndex].value;

    // get submetadata and metadata options from xml
    var subMetaDataOptions = xml.getElementsByTagName('SUBMETADATAOPTION');
    var metaDataOptions = xml.getElementsByTagName('METADATAOPTION');
    var subMetaDataFields = xml.getElementsByTagName('SUBMETADATAFIELD');
    var metaDataFields = xml.getElementsByTagName('METADATAFIELD');

    // get metadata option
    var mdOption = null;
    for (var i=0, len=metaDataOptions.length; i<len; i++)
    {
        if (metaDataOptions[i].getAttribute('ID') == mdOptionId) {
            mdOption = metaDataOptions[i];
            break;
        }
    }
    
    // get metadata field
    var mdFieldId = element.id.split('_')[1];
    var mdField = null;
    for (var i=0, len=metaDataFields.length; i<len; i++)
    {
        if (metaDataFields[i].getAttribute('ID') == mdFieldId) {
            mdField = metaDataFields[i];
            break;
        }
    }
    
    var subMDFieldStr = "submetadatafieldid_" + mdField.getAttribute('SubMDFieldID') + "_type_sublist";
    var subMDField = $(subMDFieldStr);
    if (!subMDField) return;
    if (mdOptionId != '-1') {
        for (var i=0, len=subMDField.options.length; i<len; i++) {
            if (subMDField.options[i].value == mdOption.getAttribute('SubMDValueID')) {
                subMDField.options[i].selected = true;
            } else {
                subMDField.options[i].selected = false;
            }
        }
    } else {
        subMDField.options[0].selected = true;
        for (var i=1, len=subMDField.options.length; i<len; i++) {
            subMDField.options[i].selected = false;
        }
    }
}

// function to update subMD option
function updateClientColor (element) {

    if (activeEditor.systemLevel != 4) return;
    var xml = assetRequest.responseXML;

    // get id for metadata field selection
    var mdOptionId = element.options[element.selectedIndex].value;

    // get metadata options from xml
    var metaDataOptions = xml.getElementsByTagName('METADATAOPTION');

    // get metadata option
    var mdOption = null;
    for (var i=0, len=metaDataOptions.length; i<len; i++)
    {
        if (metaDataOptions[i].getAttribute('ID') == mdOptionId) {
            mdOption = metaDataOptions[i];
            break;
        }
    }
    
    if (mdOption.getAttribute('MDFieldID') != "1") return;
    
    // get metadataoption color
    var color = "#" + mdOption.getAttribute('Color');
    
    $('assetEditor_Color').style.backgroundColor = color;

}

// function to load day part restrictions
function loadDPR(num) {
    var checkBoxStr = ""
    if (activeEditor.systemLevel == 4) {
        checkBoxStr = "assetDPR";
    } else if (activeEditor.systemLevel == 3) {
        checkBoxStr = "comboDPR";
    } else if (activeEditor.systemLevel == 2) {
        checkBoxStr = "eventDPR";
    } else if (activeEditor.systemLevel == 1) {
        checkBoxStr = "packageDPR";
    }
    
    var bitString = convertIntToBitString(num);
    
    for (var i=1; i<=24; i++){
        var checkStr = checkBoxStr + i;
        var checkEl = $(checkStr);
        if (bitString[24-i] == '1') {
            checkEl.checked = true;
        } else {
            checkEl.checked = false;
        }
    }
}

// function to save day part restrictions
function getDPR() {
    var checkBoxStr = ""
    if (activeEditor.systemLevel == 4) {
        checkBoxStr = "assetDPR";
    } else if (activeEditor.systemLevel == 3) {
        checkBoxStr = "comboDPR";
    } else if (activeEditor.systemLevel == 2) {
        checkBoxStr = "eventDPR";
    } else if (activeEditor.systemLevel == 1) {
        checkBoxStr = "packageDPR";
    }
    
    var bitString = "";
    
    for (var i=24; i>0; i--){
        var checkStr = checkBoxStr + i;
        var checkEl = $(checkStr);
        if (checkEl.checked == true) {
            bitString += "1";
        } else {
            bitString += "0";
        }
    }
    
    
    var num = convertBitStringToInt(bitString);
    
    return num;
}

// function to check or uncheck day part restrictions
function checkDayPart(checkMode){
    var checkBoxStr = ""
    if (activeEditor.systemLevel == 4) {
        checkBoxStr = "assetDPR";
    } else if (activeEditor.systemLevel == 3) {
        checkBoxStr = "comboDPR";
    } else if (activeEditor.systemLevel == 2) {
        checkBoxStr = "eventDPR";
    } else if (activeEditor.systemLevel == 1) {
        checkBoxStr = "packageDPR";
    }
    for (var i=1; i<=24; i++){
        var checkStr = checkBoxStr + i;
        var checkEl = $(checkStr);
        if (checkEl){
            if (checkMode == "all"){
                checkEl.checked = true;
            }else{
                checkEl.checked = false;
            }
        }
    }
}

// function to convert bit string to int
function convertBitStringToInt(bitString)
{    
    return parseInt(bitString,2);
}

// function to convert into to bit string
function convertIntToBitString(num) {
    var bitSring = "";
    while (num > 0) {
        bitSring = (num%2) + bitSring;
        num = Math.floor(num/2);
    }
    // pad with extra zeroes if necessary
    while (bitSring.length <24) {  // only 24 necessary for day part restrictions
        bitSring = "0" + bitSring;
    }
    
    return bitSring;
}

// convert number to hex - wgo: borrowed from web
function toHex(N) {
     if (N==null) return "00";
     N = parseInt(N); 
     if (N==0 || isNaN(N)) return "00";
     N = Math.max(0,N); 
     N = Math.min(N,255); 
     N = Math.round(N);
     return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}

// convert rgb to hex - wgo: borrowed from web
function rgb2hex(red, green, blue)
{
    return toHex(red) + toHex(green) + toHex(blue);
}

// convert cmyk to hex
function cmyk2hex(c, m, y, k) {
	c = c / 100.0;
	m = m / 100.0;
	y = y / 100.0;
	k = k / 100.0;
	
	var r = c * (1.0 - k) + k;
	var g = m * (1.0 - k) + k;
	var b = y * (1.0 - k) + k;

    r = (1.0 - r) * 255.0 + 0.5;
    g = (1.0 - g) * 255.0 + 0.5;
    b = (1.0 - b) * 255.0 + 0.5;
	
    return toHex(r) + toHex(g) + toHex(b);
}

// function to show hot keys
function showHotKeys(){
    var hotKeyId = "";
    
    if (activeEditorPageId == 'scheduleEditor') {
        hotKeyId = "draggablehotkeys_packages";
	} else if (activeEditorPageId == 'packageEditor') {
        hotKeyId = "draggablehotkeys_events";
	} else if (activeEditorPageId == 'eventEditor') {
        hotKeyId = "draggablehotkeys_combos";
    } else if (activeEditorPageId == 'multiPackage') {
        hotKeyId = "draggablehotkeys_multiPackage";
    } else if (activeEditorPageId == 'liveControl') {
        hotKeyId = "draggablehotkeys_liveControl";
    }
    var hotKeyEl = $(hotKeyId);
    if (hotKeyEl){
        hotKeyEl.style.display = "block";
    }
}

function hideHotKeys(){
    var hkPackages = $('draggablehotkeys_packages');
    var hkEvents = $('draggablehotkeys_events');
    var hkCombos = $('draggablehotkeys_combos');
    if (hkPackages) hkPackages.style.display = "none";
    if (hkEvents) hkEvents.style.display = "none";
    if (hkCombos) hkCombos.style.display = "none";
}

function showLoop() {
    // reset loop popup
    var inputs = $('loopPopup').getElementsByTagName('input');
    inputs[0].checked = true;
    inputs[1].checked = false;
    // clear time list
    var timeList = $('loopSelect');
    var timeOptions = timeList.immediateDescendants();
    for (var i=1, len=timeOptions.length; i<len; i++) {
        timeOptions[i].remove();
    }
    
    // populate list
    if (activeEditor.systemLevel == 0) {  // slotted list
        var selectedId = activeEditor.selectedCell.id;
        var startIndex = parseInt(selectedId.substr(selectedId.indexOf('drop_') + 5),10);
        for (var i=(startIndex+1), len=activeEditor.timeStrs.length; i<len; i++) {
            var optionEl = document.createElement('option');
            optionEl.value = activeEditor.timeStrs[i];
            optionEl.text = activeEditor.timeStrs[i];
            timeList.options.add(optionEl);
        }
    } else {  // timeline list
        // get current list and its index
        var listNode = activeEditor.selectedCell.parentNode;   
        var listIndex = parseInt(listNode.id.substr(listNode.id.indexOf('ddList_') + 7),10);
        var listEls = listNode.immediateDescendants();
        // get start duration
        var cumTime = [0,0,0,0,0,0];
        var activePeca = activeEditor.getPeca(activeEditor.selectedCell);
        var indexNode = listNode.firstDescendant();
        while (indexNode != activeEditor.selectedCell) {
            var indexPeca = activeEditor.getPeca(indexNode);
            cumTime = activeEditor.ddLists[listIndex].addTime(cumTime, indexPeca.duration);
            if (indexNode.next()) {
                indexNode = indexNode.next();
            } else {
                break;
            }
        }
        // add duration of activePeca as well
        cumTime = activeEditor.ddLists[listIndex].addTime(cumTime, activePeca.duration);
        
        // get time string start
        var startIndex = 0;
        var cumTimeStr = parseInt(cumTime[3],10).toPaddedString(2,10) + ":" + parseInt(cumTime[4],10).toPaddedString(2,10) + ":" +  parseInt(cumTime[5],10).toPaddedString(2,10);
        for (var i=0, len=activeEditor.timeSlots.length; i<len; i++) {
            if (cumTimeStr == padDurationStr(activeEditor.timeSlots[i])) {
                startIndex = i;
                break;
            }
        }
        // populate duration select
        for (var i=startIndex, len=activeEditor.timeSlots.length; i<len; i++) {
            var optionEl = document.createElement('option');
            optionEl.value = activeEditor.timeSlots[i];
            optionEl.text = activeEditor.timeSlots[i];
            timeList.options.add(optionEl);
        }
        // add final option because it's not in time slots list
        var optionEl = document.createElement('option');
        optionEl.value = "30:00";
        optionEl.text = "30:00";
        timeList.options.add(optionEl);  
    }
    
    $('loopPopup').style.display = "block";
    coverPageForAlert($('loopPopup'));
}

function updateLoopOptions() {
    var inputs = $('loopPopup').getElementsByTagName('input');
    if ($('loopSelect').selectedIndex > 0) {
        inputs[0].checked = false;
        inputs[1].checked = true;
    }
}

// function to check loop in case of overwriting
function checkLoop() {
    // check only needs to be done for slotted list and loop until option 
    var inputs = $('loopPopup').getElementsByTagName('input');
    var timeList = $('loopSelect');
    if ( (activeEditor.systemLevel == 0) && (inputs[1].checked) ) {  // check for overwriting
        var selectedId = activeEditor.selectedCell.id;
        var startIndex = parseInt(selectedId.substr(selectedId.indexOf('drop_') + 5),10);
        var endTime = timeList.options[timeList.selectedIndex].value;
        // get index of end time
        var endIndex = 0;
        for (var i=0, len=activeEditor.timeStrs.length; i<len; i++) {
            if (endTime == activeEditor.timeStrs[i]) {
                endIndex = i;
                break;
            }
        }
        var selectedListId = selectedId.substring(0,selectedId.indexOf('_drop'));
        var listEls = $(selectedListId).immediateDescendants();
        
	    // check if any of the loop spots are occupied
        for (var i=(startIndex+1); i<=endIndex; i++) {
            if (listEls[i].firstDescendant()) {
                var spanTxt = "Warning";
                var labelTxt = "Some currently scheduled items will be replaced during loop.  Continue?";
                var onClickYes = "hideYesNoAlert(); processLoop();";
                var onClickNo = "hideYesNoAlert();";
                showYesNoAlert(spanTxt, labelTxt, onClickYes, onClickNo);
                return;
            }
        }
    }
    // if the check succeeds, process the loop
    processLoop();
}

// function to perform the requested loop
function processLoop() {
    var inputs = $('loopPopup').getElementsByTagName('input');
    var timeList = $('loopSelect');
    // get peca to make copies
    var loopPeca = null;
    if (activeEditor.selectedCell.match('div')) {
        loopPeca = activeEditor.getPeca(activeEditor.selectedCell.firstDescendant());
    } else {
        loopPeca = activeEditor.getPeca(activeEditor.selectedCell);
    }
    
    if (activeEditor.systemLevel == 0) { // slotted implementation
        if (inputs[0].checked) { // fill available
            var selected = activeEditor.selectedCell;
            while ( (selected.next()) && (!selected.next().firstDescendant()) ) {
                selected = selected.next();
                var newPeca = loopPeca.copy();
                var newPecaEl = newPeca.render();
                selected.appendChild(newPecaEl);
                addDrag(newPecaEl);
		        activeEditor.draggablePecas.push(newPeca);
		        activeEditor.validatePackage(newPecaEl, selected);
            }
        } else { // loop until
            var selectedId = activeEditor.selectedCell.id;
            var startIndex = parseInt(selectedId.substr(selectedId.indexOf('drop_') + 5),10);
            var endTime = timeList.options[timeList.selectedIndex].value;
            // get index of end time
            var endIndex = 0;
            for (var i=0, len=activeEditor.timeStrs.length; i<len; i++) {
                if (endTime == activeEditor.timeStrs[i]) {
                    endIndex = i;
                    break;
                }
            }
            var selectedListId = selectedId.substring(0,selectedId.indexOf('_drop'));
	        var listEls = $(selectedListId).immediateDescendants();
            
        	// process the loop, removing any slots that are occupied
            for (var i=(startIndex+1); i<=endIndex; i++) {
                if (listEls[i].firstDescendant()) listEls[i].firstDescendant().remove();
                var newPeca = loopPeca.copy();
                var newPecaEl = newPeca.render();
                listEls[i].appendChild(newPecaEl);
                addDrag(newPecaEl);
		        activeEditor.draggablePecas.push(newPeca);
		        activeEditor.validatePackage(newPecaEl, listEls[i]);
            }
        }
    } else { // timeline implementation
        var endTimeStr = "";
        if (inputs[0].checked) { // fill available
            endTimeStr = "30:00";
        } else { // loop until
            endTimeStr = timeList.options[timeList.selectedIndex].value;
        }
        // get current list and its index
        var listNode = activeEditor.selectedCell.parentNode;   
        var listIndex = parseInt(listNode.id.substr(listNode.id.indexOf('ddList_') + 7),10);
        var listEls = listNode.immediateDescendants();
        // get start duration
        var cumTime = [0,0,0,0,0,0];
        var activePeca = activeEditor.getPeca(activeEditor.selectedCell);
        var indexNode = listNode.firstDescendant();
        while (indexNode != activeEditor.selectedCell) {
            var indexPeca = activeEditor.getPeca(indexNode);
            cumTime = activeEditor.ddLists[listIndex].addTime(cumTime, indexPeca.duration);
            if (indexNode.next()) {
                indexNode = indexNode.next();
            } else {
                break;
            }
        }
        // add duration of activePeca as well
        cumTime = activeEditor.ddLists[listIndex].addTime(cumTime, activePeca.duration);
        var cumTimeStr = parseInt(cumTime[4],10).toPaddedString(2,10) + ":" +  parseInt(cumTime[5],10).toPaddedString(2,10);
        // loop until time hits 30 min
        var selected = activeEditor.selectedCell;
        var loopCumTime = cumTime;
        var loopCumTimeStr = cumTimeStr;
        loopCumTime = activeEditor.ddLists[listIndex].addTime(loopCumTime, loopPeca.duration);
        loopCumTimeStr = parseInt(loopCumTime[4],10).toPaddedString(2,10) + ":" +  parseInt(loopCumTime[5],10).toPaddedString(2,10);
        while (loopCumTimeStr <= endTimeStr) { // loopCumTimeStr prevents looping past end time
            var newPeca = loopPeca.copy();
            var newPecaEl = newPeca.render();
            if (selected.nextSiblings().length > 0) {
                var next = selected.next();
	            listNode.insertBefore(newPecaEl, next);
            } else {  // paste to end of list
	            listNode.appendChild(newPecaEl);
            } 
	        addDrag(newPecaEl);
	        activeEditor.draggablePecas.push(newPeca);
	        loopCumTime = activeEditor.ddLists[listIndex].addTime(loopCumTime, newPeca.duration);
	        loopCumTimeStr = parseInt(loopCumTime[4],10).toPaddedString(2,10) + ":" +  parseInt(loopCumTime[5],10).toPaddedString(2,10);
	        selected = selected.next();
        }
    } 
}

function hideLoop() {
    uncoverPageForAlert();
    $('loopPopup').style.display = "none";
}

var activeColorSelectDiv = null;
function showColorSelector(colorDiv){
    var colorEl = $('colorSelector');
    if (colorEl){
        activeColorSelectDiv = colorDiv;
        colorEl.style.display = "block";
    }
    activeColorSelectDiv = colorDiv;
}

function showColorSelectorMD(colorDiv){
    var colorEl = $('colorSelectorMD');
    if (colorEl){
        activeColorSelectDiv = colorDiv;
        //var top = Position.realOffset(activeColorSelectDiv)[1] + 25;
        //colorEl.parentNode.style.top = top + "px";
        colorEl.style.display = "block";
    }
}

function assignColor(selectedColorNode){
    //selectedColor = "#" + selectedColorNode.innerHTML;
    selectedColor = selectedColorNode.innerHTML;
    $('selectedColorHex').value = selectedColor;
//    return true;
//    $('colorSelectHexAlert').focus();
    //changeColor(selectedColor);
    //changeColor(selectedColor);
}

function assignColorMD(selectedColorNode){
    selectedColor = selectedColorNode.innerHTML;
    $('selectedColorHexMD').value = selectedColor;
//    return true;
//    $('colorSelectHexAlertMD').focus();
    //changeColor(selectedColor);
}

function changeColorMD() {
    if (selectedColorCheckHexMD() == false) return;

    if (activeColorSelectDiv) {
        var newColor = "#" + $('selectedColorHexMD').value;
        activeColorSelectDiv.style.backgroundColor = newColor;
        hideColorSelectorMD();
    }
}

// function to check hex field on textbox change
function selectedColorCheckHex() {
    // check validity of hex value
    var valueHex = $('selectedColorHex').value.trim();
    if (valueHex != "" && !(valueHex.match(/^([0-9]|[A-F]|[a-f]){6}$/))) { // not valid hex
        $('colorSelectHexAlert').style.display = "block";
        $('colorSelectHexAlert').focus();
        return false;
    } else {
        $('colorSelectHexAlert').style.display = "none";
        return true;
	}
}

function changeColor(selectedColor){
    if (selectedColorCheckHex() == false) return;
    if (activeColorSelectDiv) {
        if (activeColorSelectDiv.className == "colorSelectBox") {
            activeColorSelectDiv.style.backgroundColor = selectedColor;
        } else if (activeColorSelectDiv.descendantOf(activeEditor.containerId)) { // update all occurances
            // find all occurrences to update
            var peca = activeEditor.getPeca(activeColorSelectDiv);
            // change color in db, if it fails return
            var changeColorRequest = new XMLHttpRequest();
            var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_UpdateColor\" objID=\"" + peca.dbId + "\" objLevel=\"" + peca.itemType + 
                            "\" color=\"" + selectedColor.substr(1) + "\" />";
            var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
            xmlStr += "<ROOT>";
            xmlStr += sProc;
            xmlStr += "</ROOT>";
            var url = "AjaxPost.aspx";
            changeColorRequest.open('POST', url, false);
            changeColorRequest.setRequestHeader("Content-Type", "text/xml");
            changeColorRequest.send(xmlStr);
            // wait for return before proceeding
	        if (changeColorRequest.readyState == 4) {
		        if (changeColorRequest.status == 200) {
		            if (changeColorRequest.responseText == 0) {
		                alert('There was an error with the request.  Unable to update color.  Please try again.');
		                return;
		            }
		        }
	        }             
            // if success, then update color on page
            for (var i=0, len=activeEditor.draggablePecas.length; i<len; i++) {
                if (peca.dbId == activeEditor.draggablePecas[i].dbId) {
                    // change color property
                    activeEditor.draggablePecas[i].thisColor = selectedColor;
                    activeEditor.draggablePecas[i].fontColor = activeEditor.draggablePecas[i].assignFontColor();
                    // change color of element
                    var pecaEl = $(activeEditor.draggablePecas[i].tagId);
                    if (pecaEl) {
                        pecaEl.style.backgroundColor = selectedColor;
                        pecaEl.style.color = activeEditor.draggablePecas[i].fontColor;
                    }
                }    
            }
            // change any occurrences in hot key popup
            for (var i=0, len=activeEditor.hotKeys.length; i<len; i++) {
                if (activeEditor.hotKeys[i] != null) {
                    if (peca.dbId == activeEditor.hotKeys[i].dbId) {
                        // change color property
                        activeEditor.hotKeys[i].thisColor = selectedColor;
                        activeEditor.hotKeys[i].fontColor = activeEditor.hotKeys[i].assignFontColor();
                        // change color of hot key element
                        //var pecaEl = $(activeEditor.hotKeys[i].id);
                        var pecaEl = null;
                        var pecaStr = "";
                        if (activeEditor.systemLevel == 0) pecaStr = "package_HK" + i;
                        if (activeEditor.systemLevel == 1) pecaStr = "event_HK" + i;
                        if (activeEditor.systemLevel == 2) pecaStr = "combo_HK" + i;
                        pecaEl = $(pecaStr);
                        if (pecaEl) {
                            pecaEl.style.backgroundColor = selectedColor;
                            pecaEl.style.color = activeEditor.hotKeys[i].fontColor;
                        }
                    }
                }
            }
        }
    }
    hideColorSelector();
}

// ajax state change handler
function processChangeColorRequest () {
	if (changeColorRequest.readyState == 4) {
		if (changeColorRequest.status == 200) {
		    if (changeColorRequest.responseText > 0) alert('color updated');
		}
	} 
}

function hideColorSelector(){
    var colorEl = $('colorSelector');
    if (colorEl){
        $('selectedColorHex').value = "";
        $('colorSelectHexAlert').style.display = "none";
        colorEl.style.display = "none";
    }
    activeColorSelectDiv = null;
}

function hideColorSelectorMD(){
    var colorEl = $('colorSelectorMD');
    if (colorEl){
        $('selectedColorHexMD').value = "";
        $('colorSelectHexAlertMD').style.display = "none";
        colorEl.style.display = "none";
    }
    
    activeColorSelectDiv = null;
}

function showGetInfo () {
    $('getInfoPanel').style.display = "block";
    // if region selected show multiple selected
    if ( activeEditor.selectedRegion.length > 1 ) {
        // hide "Nothing selected"
        $('getInfo_NothingSelected').style.display = "none";
	    
        var container = $('infoInner');
        // delete any previous contents
        var currentEls = container.immediateDescendants();
        for (var i=0, len=currentEls.length; i<len; i++) {
            currentEls[i].remove();
        }
	    
        // show multiple selected
        $('getInfo_MultipleSelected').style.display = "block";
    } else if ( (activeEditorPageId == 'liveControl') && (searchChoice == 'Package') ) {
        activeEditor.updateGetInfo($('liveControlPackageResults').options[$('liveControlPackageResults').selectedIndex].value);
    } else if (activeEditor.dragContainer.firstDescendant()) {
        activeEditor.updateGetInfo(activeEditor.dragContainer.firstDescendant().id);
    }
}

function resetGetInfo () {
    $('getInfoPanel').style.display = "none";
    $('getInfo_NothingSelected').style.display = "block";
     $('getInfo_MultipleSelected').style.display = "none";
    var infoEls = $('infoInner').immediateDescendants();
    for (var i=0, len=infoEls.length; i<len; i++) {
        infoEls[i].remove();
    }
}

// function to hide/show options based on user access
function applyUserAccess(page) {
    var accessIds = accessList.immediateDescendants();
    for (var i=0, len=accessIds.length; i<len; i++) {
           
        // scheduler menu
        if (accessIds[i].value == '100') {$('navScheduler').style.display = "inline"; continue;}
        if (accessIds[i].value == '101') {$('navScheduler_Schedules').style.display = "inline"; continue;}
        if (accessIds[i].value == '102') {$('navScheduler_Packages').style.display = "inline"; continue;}
        if (accessIds[i].value == '103') {$('navScheduler_Events').style.display = "inline"; continue;}
        if (accessIds[i].value == '104') {$('navScheduler_Combos').style.display = "inline"; continue;}
        if (accessIds[i].value == '105') {$('navScheduler_Assets').style.display = "inline"; continue;}

        // live control menu
        if (accessIds[i].value == '110') {
            $('navLiveControl').style.display = "inline";
            $('navLiveControlSub').style.display = "inline";
            continue;
        }
        
        // admin menu
        if (accessIds[i].value == '120') {$('navAdmin').style.display = "inline"; continue;}
        if (accessIds[i].value == '121') {$('navAdmin_Users').style.display = "inline"; continue;}
        if (accessIds[i].value == '122') {$('navAdmin_MetaData').style.display = "inline"; continue;}
        if (accessIds[i].value == '123') {$('navAdmin_DataTags').style.display = "inline"; continue;}
        if (accessIds[i].value == '124') {$('navAdmin_ImageTags').style.display = "inline"; continue;}
        if (accessIds[i].value == '125') {$('navAdmin_StringTags').style.display = "inline"; continue;}
        
        // reporting menu
        if (accessIds[i].value == '140') {$('navReporting').style.display = "inline"; continue;}
        if (accessIds[i].value == '141') {$('navReporting_SignUsage').style.display = "inline"; continue;}
        if (accessIds[i].value == '142') {$('navReporting_DailyRun').style.display = "inline"; continue;}
        if (accessIds[i].value == '143') {$('navReporting_DailyRunDetail').style.display = "inline"; continue;}
        if (accessIds[i].value == '144') {$('navReporting_PreRunSchedule').style.display = "inline"; continue;}
        if (accessIds[i].value == '145') {$('navReporting_MakeGoods').style.display = "inline"; continue;}
        if (accessIds[i].value == '146') {$('navReporting_Avails').style.display = "inline"; continue;}
        if (accessIds[i].value == '147') {$('navReporting_Tasks').style.display = "inline"; continue;}
        
        // view schedule
        if (accessIds[i].value == '201') {
            if (page == "ScheduleList") {$('contentContainer').style.display = "block"; continue;}
            if ( (page == "Editor") && (activeEditorPageId == 'scheduleEditor') ) {
                $('contentContainer').style.display = "block";
                continue;
            }
        }
        
        // view package
        if (accessIds[i].value == '202') {
            if (page == "PackageList") {$('contentContainer').style.display = "block"; continue;}
            if (page == "MultiPackage") {$('contentContainer').style.display = "block"; continue;}
            if ( (page == "Editor") && (activeEditorPageId == 'packageEditor') ) {
                $('contentContainer').style.display = "block";
                continue;
            }
        }
        
        // view event
        if (accessIds[i].value == '203') {
            if (page == "EventList") {$('contentContainer').style.display = "block"; continue;}
            if ( (page == "Editor") && (activeEditorPageId == 'eventEditor') ) {
                $('contentContainer').style.display = "block";
                continue;
            }
        }
        
        // view combo
        if (accessIds[i].value == '204') {
            if (page == "ComboList") {$('contentContainer').style.display = "block"; continue;}
            if ( (page == "Editor") && (activeEditorPageId == 'comboEditor') ) {
                $('contentContainer').style.display = "block";
                continue;
            }
        }
        
        // view asset 
        if (accessIds[i].value == '205') {
            if (page == "AssetList") {$('contentContainer').style.display = "block"; continue;}
            if ( (page == "Editor") && (activeEditorPageId == 'assetEditor') ) {
                $('contentContainer').style.display = "block";
                continue;
            }
        }
        
        // view task panel 
        if ( (accessIds[i].value == '206') && (activeEditorPageId == 'assetEditor') ) {
            $('assetEditor_TaskContainer').style.display = "block";
            continue;
        }
        
        // view live control
        if ( (accessIds[i].value == '210') && (page == "LiveControl") ) {$('contentContainer').style.display = "block"; continue;}
        // view users
        if ( (accessIds[i].value == '221') && (page == "Users") ) {$('contentContainer').style.display = "block"; continue;}
        // view meta-data
        if ( (accessIds[i].value == '222') && (page == "MetaData") ) {$('contentContainer').style.display = "block"; continue;}
        // view data tags
        if ( (accessIds[i].value == '223') && (page == "DataTags") ) {$('contentContainer').style.display = "block"; continue;}
        // view image tags
        if ( (accessIds[i].value == '224') && (page == "ImageTags") ) {$('contentContainer').style.display = "block"; continue;}
        // view string tags
        if ( (accessIds[i].value == '225') && (page == "StringTags") ) {$('contentContainer').style.display = "block"; continue;}
        // view sign usage by customer
        if ( (accessIds[i].value == '241') && (page == "ReportSignUsage") ) {$('contentContainer').style.display = "block"; continue;}
        // view daily run
        if ( (accessIds[i].value == '242') && (page == "ReportDailyRun") ) {$('contentContainer').style.display = "block"; continue;}
        // view daily run detail
        if ( (accessIds[i].value == '243') && (page == "ReportDailyDetail") ) {$('contentContainer').style.display = "block"; continue;}
        // view pre-run
        if ( (accessIds[i].value == '244') && (page == "ReportPreRun") ) {$('contentContainer').style.display = "block"; continue;}
        // view make goods
        if ( (accessIds[i].value == '245') && (page == "ReportMakeGoods") ) {$('contentContainer').style.display = "block"; continue;}
        // view avails
        if ( (accessIds[i].value == '246') && (page == "ReportAvails") ) {$('contentContainer').style.display = "block"; continue;}
        // view tasks report
        if ( (accessIds[i].value == '247') && (page == "ReportTasks") ) {$('contentContainer').style.display = "block"; continue;}

        // edit schedule
        if (accessIds[i].value == '301') {
            if ( (page == "Editor") && (activeEditorPageId == 'scheduleEditor') ) {
                $('scheduleEditor_Save').style.display = "block";
                $('scheduleEditor_Cancel').style.display = "block";
                continue;
            }
        }
        
        // edit package
        if (accessIds[i].value == '302') {
            if (page == "PackageList") {
                $('btnDisableRow').style.display = "block";
                $('btnEnableRow').style.display = "block";
                continue;
            }
            if (page == "MultiPackage") {
                $('multiPackage_Save').style.display = "block";
                $('multiPackage_Cancel').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'packageEditor') && (editors.length < 1) ) {
                $('packageEditor_Save').style.display = "block";
                $('packageEditor_Cancel').style.display = "block";
                continue;
            }
        }
        
        // edit event
        if (accessIds[i].value == '303') {
            if (page == "EventList") {
                $('btnDisableRow').style.display = "block";
                $('btnEnableRow').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'eventEditor') ) {
                $('eventEditor_Save').style.display = "block";
                $('eventEditor_Cancel').style.display = "block";
                continue;
            }
        }
        
        // edit combo
        if (accessIds[i].value == '304') {
            if (page == "ComboList") {
                $('btnDisableRow').style.display = "block";
                $('btnEnableRow').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'comboEditor') ) {
                $('comboEditor_Save').style.display = "block";
                $('comboEditor_Cancel').style.display = "block";
                continue;
            }
        }
        
        // edit asset
        if (accessIds[i].value == '305') {
            if (page == "AssetList") {
                $('btnDisableRow').style.display = "block";
                $('btnEnableRow').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'assetEditor') ) {
                $('assetEditor_Save').style.display = "block";
                $('assetEditor_Cancel').style.display = "block";
                continue;
            }
        }
        
        // edit task
        if (accessIds[i].value == '306') {
            if ( (page == "Editor") && (activeEditorPageId == 'assetEditor') ) {
                $('assetEditor_TaskContainer').style.display = "block"; 
                $('assetEditor_ResetFields').style.display = "block";
                $('assetEditor_UpdateTask').style.display = "block";
                $('assetEditor_DeleteTask').style.display = "block"; 
                continue;
            }
        }
        
        // NOTE: edit admin screens are handled server side on the individual pages
                
        // new package
        if (accessIds[i].value == '402') {
            if (page == "PackageList") {
                $('btnDuplicateRow').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'packageEditor') && (editors.length < 1) ) {
                $('packageEditor_SaveCopy').style.display = "block";
                $('packageEditorCreateNew').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'packageEditor') && (editors.length > 0) ) {
                $('packageEditor_Save').style.display = "block";
                $('packageEditor_Cancel').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'scheduleEditor') ) {
                $('scheduleEditor_NewPackage').style.display = "block";
                continue;
            }
        }
        
        // new event
        if (accessIds[i].value == '403') {
            if (page == "EventList") {
                $('btnDuplicateRow').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'eventEditor') && (editors.length < 1) ) {
                $('eventEditor_SaveCopy').style.display = "block";
                $('eventEditorCreateNew').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'packageEditor') ) {
                $('packageEditor_NewEvent').style.display = "block";
                continue;
            }
        }
        
        // new combo
        if (accessIds[i].value == '404') {
            if (page == "ComboList") {
                $('btnDuplicateRow').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'comboEditor') && (editors.length < 1) ) {
                $('comboEditor_SaveCopy').style.display = "block";
                $('comboEditorCreateNew').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'eventEditor') ) {
                $('eventEditor_NewCombo').style.display = "block";
                continue;
            }
        }
        
        // new asset
        if (accessIds[i].value == '405') {
            if (page == "AssetList") {
                $('btnDuplicateRow').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'assetEditor') && (editors.length < 1) ) {
                $('assetEditor_SaveCopy').style.display = "block";
                $('assetEditorCreateNew').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'eventEditor') ) {
                $('eventEditor_NewAsset').style.display = "block";
                continue;
            }
            if ( (page == "Editor") && (activeEditorPageId == 'comboEditor') ) {
                $('comboEditor_NewAsset').style.display = "block";
                continue;
            }
        }
        
        // new task
        if (accessIds[i].value == '406') {
            if ( (page == "Editor") && (activeEditorPageId == 'assetEditor') ) {
                $('assetEditor_AddTask').style.display = "block";
                continue;
            }
        }
        
    }
}

function escapeForXML(strInput)
{
  // replace special characters that will error out in xml
  strInput=strInput.replace(/&/g,"&amp;");  // replace & with &amp;
  strInput=strInput.replace(/</g,"&lt;");	// replace < with &lt;
  strInput=strInput.replace(/>/g,"&gt;");	// replace > with &gt;
  strInput=strInput.replace(/"/g,"&quot;");	// replace " with &quot;
  strInput=strInput.replace(/'/g,"&apos;");	// replace ' with &apos;
  
  return(strInput);
}

function replaceExtendedASCIIChars(strInput)
{
  // replace extended ascii chars with printable chars
  strInput=strInput.replace(/[‘’]/g,"&apos;");  // replace directional single quotes with apostrophe
  strInput=strInput.replace(/[“”]/g,"&quot;");	// replace directional double quotes with double quote
  strInput=strInput.replace(/[•–—]/g,"&#45;");	// replace certain dash characters with a regular dash (minus sign)
  
  return(strInput);
}
    
    